flask做一个登录注册的博客系统代码,带有mysql数据库,数据库通过SQLAlchemy实现
时间: 2024-06-10 15:04:49 浏览: 22
好的,以下是一个简单的使用 Flask 和 SQLAlchemy 的登录注册博客系统代码:
```python
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/dbname'
app.config['SECRET_KEY'] = 'secretkey'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), unique=True, nullable=False)
email = db.Column(db.String(100), unique=True, nullable=False)
password_hash = db.Column(db.String(100), nullable=False)
posts = db.relationship('Post', backref='author', lazy=True)
def __repr__(self):
return '<User %r>' % self.username
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return '<Post %r>' % self.title
@app.route('/')
def home():
posts = Post.query.order_by(Post.date_posted.desc()).all()
return render_template('home.html', posts=posts)
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
email = request.form['email']
password = request.form['password']
confirm_password = request.form['confirm_password']
if not username or not email or not password or not confirm_password:
error = 'Please fill out all fields'
return render_template('register.html', error=error)
if password != confirm_password:
error = 'Passwords do not match'
return render_template('register.html', error=error)
existing_user = User.query.filter_by(username=username).first()
if existing_user:
error = 'Username already exists'
return render_template('register.html', error=error)
existing_email = User.query.filter_by(email=email).first()
if existing_email:
error = 'Email already registered'
return render_template('register.html', error=error)
user = User(username=username, email=email)
user.set_password(password)
db.session.add(user)
db.session.commit()
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if not username or not password:
error = 'Please enter a username and password'
return render_template('login.html', error=error)
user = User.query.filter_by(username=username).first()
if not user or not user.check_password(password):
error = 'Incorrect username or password'
return render_template('login.html', error=error)
return redirect(url_for('home'))
return render_template('login.html')
@app.route('/new_post', methods=['GET', 'POST'])
def new_post():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
if not title or not content:
error = 'Please fill out all fields'
return render_template('new_post.html', error=error)
post = Post(title=title, content=content, author=current_user)
db.session.add(post)
db.session.commit()
return redirect(url_for('home'))
return render_template('new_post.html')
if __name__ == '__main__':
app.run(debug=True)
```
注意将 `username`, `password`, 和 `dbname` 替换为你自己的数据库连接信息,以及将 `secretkey` 替换为一个随机的字符串。同时,还需要将模板文件 `home.html`, `login.html`, `register.html`, 和 `new_post.html` 创建并放置在 `templates` 文件夹下,以及静态文件 `style.css` 创建并放置在 `static` 文件夹下。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)