python - 怎么用flask+mysql来实现一个简单的用户注册和登陆效果的页面呢?请不要用任何ORM
PHP中文网
PHP中文网 2017-04-17 14:36:35
0
5
434

首先,请不要用任何ORM(当然SQLAlchemy,Flask-SQLAlchemy也不要用)
初学flask,于是参照http://dormousehole.readthedocs.org/en/latest/tutorial/introduction.ht...
实际用到的关键代码在这里:https://github.com/mitsuhiko/flask/blob/0.10.1/examples/flaskr/flaskr....
发现网上都是用的sqlite3,或者就是mysql+Flask-SQLAlchemy之类的。
然后很痛苦,本来一个连flask+mysql做用户注册和登陆的效果都不会实现的人,怎么可能轻易看的懂flask+mysql+mysql+Flask-SQLAlchemy的呢。
问了群里好多人,都说用mysql跟sqlite3是一样的,可是我发现多少是有些区别,至少自己搞了一周还是没搞定,不知从何弄起,感觉好痛苦。
可否有大神帮忙弄一个成功的,代码分享下。不胜感激啊!
最好是先一份flask+mysql,再来一份flask+mysql+Flask-SQLAlchemy什么的,便于比较学习。先说声谢谢了

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(5)
洪涛

Can you write SQL?
If you don’t understand this, don’t worry about it yet, review the basics, and sharpen your sword before chopping firewood.

pythonimport os, sys, string
import MySQLdb

# 连接数据库 
try:
    conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1')
except Exception, e:
    print e
    sys.exit()

# 获取cursor对象来进行操作
cursor = conn.cursor()
# 创建表
sql = "create table if not exists test1(name varchar(128) primary key, age int(4))"
cursor.execute(sql)
# 插入数据
sql = "insert into test1(name, age) values ('%s', %d)" % ("zhaowei", 23)
try:
    cursor.execute(sql)
except Exception, e:
    print e

sql = "insert into test1(name, age) values ('%s', %d)" % ("张三", 21)
try:
    cursor.execute(sql)
except Exception, e:
    print e

# 插入多条
sql = "insert into test1(name, age) values (%s, %s)"
val = (("李四", 24), ("王五", 25), ("洪六", 26))
try:
    cursor.executemany(sql, val)
except Exception, e:
    print e

#查询出数据
sql = "select * from test1"
cursor.execute(sql)
alldata = cursor.fetchall()
# 如果有数据返回,就循环输出, alldata是有个二维的列表
if alldata:
    for rec in alldata:
        print rec[0], rec[1]


cursor.close()
conn.close()
Peter_Zhu

If you don’t use a ready-made ORM, you can learn to write one yourself. . If you want to write it yourself, you can refer to Liao Shen’s ORM

左手右手慢动作

There are many ways to connect python and mysql, right? I'm connected. Isn't it possible to use SQL directly without using ORM?

Peter_Zhu

You can refer to Flask’s official example: minitwit, but the database uses sqlite

小葫芦

Isn’t there a tutorial? http://docs.jinkan.org/docs/f...

A simple user registration and login page, just two parts.

  1. Involves the database, storing user data (registration), and reading out user data (login verification). Just figure out how to use python to connect and operate the database, and understand sql database statements. sqlite and mysql are similar. You will understand after a few glances and tries.

  2. Website program, how does the front-end send a form (don’t tell me, you don’t know this?) The back-end gets the request sent by the user, verifies whether it can log in with the data in the database, and then how to save the user’s login information after logging in, that is The cookie used, but in flask is session (in fact, session is also a cookie, flask encapsulates it and becomes an encrypted cookie)

In short, if you follow the official tutorial carefully. It is not difficult to complete the functions of user login and registration. Although these knowledge points are not bad, the coverage is still relatively broad. Database, front-end HTML, back-end program framework, if you don't know much about any of them, you will feel like you can't start.

Okay. Throw in a piece of verification login code, because flask's routing is implemented by binding functions one by one. It is quite troublesome if you want to add a piece of verification login code to each route, but it can be implemented through the decorator function. It’s quite convenient

Example

from functools import wraps
def authorize(fn):
    @wraps(fn)
    def wrapper(*args, **kwds):
        user = session.get('logged_in', None)
        if user:
            return fn(user=user)
        else:
            return redirect(url_for('signin',next=request.path))

    return wrapper
    

@app.route('/home')
@authorize
def home(**kwds):
    username = kwds['user']
    return render_template('index.html' ,username=username)
    
#加密存储密码
import os
import hashlib
def encrypt_password(password, salt=None, encryptlop=30):
    if not salt:
        salt = os.urandom(16).encode('hex') # length 32
    for i in range(encryptlop):
        password = hashlib.sha256(password + salt).hexdigest() # length 64
    return password, salt
    
#简单的错误处理
class loginError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

# 注册登录(下面的代码没有实际运行过)
# 连接数据库我是使用的是 mysql.connector 
# http://dev.mysql.com/downloads/connector/python/
# 写法和常用的MySQL-python稍有所不同
# 下面没有连接数据库的代码

@app.route('/register/', methods=['GET','POST'])
def request():
    if request.method == 'GET':
        return render_template("register.html")
    if request.method == 'POST':
        # 这里最好需要验证用户输入,我就不写了
        u = request.form['username']
        p,s = encrypt_password(request.form['password'])
        g.db.cursor.execute('INSERT INTO users (name,password,salt) VALUES (%s,%s,%s)',(u,p,s,)
        g.db.commit()
        return redirect(url_for('signin'))
        
@app.route('/signin/', methods=['GET','POST'])
def signin():
    if request.method == 'GET':
        referrer = request.args.get('next','/')
        return render_template("login.html",next=referrer)
    if request.method == 'POST':
        u = request.form['username']
        p = request.form['password']
        n = request.form['next']
        try:
            g.db.cursor.execute('SELECT `name` FROM users WHERE name = %s',(u,))
            if not g.db.cursor.fetchone():
                raise loginError(u'错误的用户名或者密码!')
            g.db.cursor.execute('SELECT `salt`,`password` FROM users WHERE name = %s',(u,))
            salt,password = g.db.cursor.fetchone()
            if encrypt_password(p,salt)[0] == password:
                session['logged_in'] = u
                return redirect(next)
            else:
                raise loginError(u'错误的用户名或者密码!')
        except loginError as e:
            return render_template('login.html', next=next,error=e.value)

@app.route('/signout/', methods=['POST'])
def signout():
    session.pop('logged_in', None)
    return redirect(url_for('home'))
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!