Python轻量级框架Flask开发web应用
from flask import Flask, render_template, request, redirect, url_for, session
from flask_sqlalchemy import SQLAlchemy
import config
app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(20), nullable=False)
password = db.Column(db.String(20), nullable=False)
def __str__(self):
return 'User: {self.username}'.format(self=self)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login/', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
else:
username = request.form.get('username')
password = request.form.get('password')
user = User.query.filter(User.username == username, User.password == password).first()
if user:
session['username'] = username
return redirect(url_for('index'))
else:
return 'Login failed.'
@app.route('/register/', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
return render_template('register.html')
else:
username = request.form.get('username')
password = request.form.get('password')
user = User(username=username, password=password)
db.session.add(user)
db.session.commit()
return redirect(url_for('login'))
@app.route('/logout/')
def logout():
session.clear()
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
这段代码是一个简单的用户登录注册系统的Flask应用示例。它展示了如何使用Flask框架结合SQLAlchemy来创建数据库模型,处理简单的登录和注册逻辑,并使用session来管理用户会话。这个示例提供了一个很好的起点,对于想要学习Flask web开发的开发者来说非常有帮助。
评论已关闭