(venv) PS C:\Users\Administrator\Desktop\code_learn\flask_exercise\tutorproject\back-end>flask run
* Serving Flask app 'madblog.py' * Debug mode: on WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:5000 Press CTRL+C to quit * Restarting with stat * Debugger is active! * Debugger PIN: 354-979-609
from flask import Flask from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from config import Config
(venv) PS C:\Users\Administrator\Desktop\code_learn\flask_exercise\tutorproject\back-end> flask shell Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32 App: tutorweb Instance: C:\Users\Administrator\Desktop\code_learn\flask_exercise\tutorproject\back-end\instance >>> tutorweb Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'tutorweb' is not defined >>> app <Flask 'tutorweb'> >>> db <SQLAlchemy sqlite:///C:\Users\Administrator\Desktop\code_learn\flask_exercise\tutorproject\back-end\tutorweb.db>
修改back-end/madblog.py,添加一个方法:
1 2 3 4 5 6 7 8
from tutorweb import create_app,db from tutorweb.models import User
deffrom_dict(self, data, new_user=False): for field in ['username', 'email']: if field in data: setattr(self, field, data[field]) if new_user and'password'in data: self.set_password(data['password'])
错误处理
创建 tutorweb/api/errors.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
from flask import jsonify from werkzeug.http import HTTP_STATUS_CODES
import re from flask import request,jsonify,url_for from tutorweb import db from tutorweb.api import bp from tutorweb.api.errors import bad_request from tutorweb.models import User
@bp.route('/users',methods=['POST']) defcreate_user(): #注册一个新用户 data=request.get_json() ifnot data: return bad_request('You must post JSON data.')
message={} if'username'notin data ornot data.get('username', None): message['username'] = 'Please provide a valid username.' pattern = '^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$' if'email'notin data ornot re.match(pattern, data.get('email', None)): message['email'] = 'Please provide a valid email address.' if'password'notin data ornot data.get('password', None): message['password'] = 'Please provide a valid password.'
if User.query.filter_by(username=data.get('username', None)).first(): message['username'] = 'Please use a different username.' if User.query.filter_by(email=data.get('email', None)).first(): message['email'] = 'Please use a different email address.' if message: return bad_request(message)
* Serving Flask app 'madblog.py' WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:5000 Press CTRL+C to quit * Restarting with stat * Debugger is active! * Debugger PIN: 354-979-609
(venv) PS C:\Users\Administrator\Desktop\code_learn\flask_exercise\tutorproject\back-end> http POST http://localhost:5000/api/users username=lisi password=123 email=lisi@163.com
http: error: ConnectionError: HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded with url: /api/users (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000022A6C404550>: Failed to establish a new connection: [WinError 10061] 由于目标计算机积极拒绝,无法连接。')) while doing a POST request to URL: http://localhost:5000/api/users
(venv) PS C:\Users\Administrator\Desktop\code_learn\flask_exercise\tutorproject\back-end> http GET http://localhost:5000/api/users/7
HTTP/1.1 404 NOT FOUND Access-Control-Allow-Origin: * Connection: close Content-Length: 207 Content-Type: text/html; charset=utf-8 Date: Mon, 24 Oct 2022 03:19:48 GMT Server: Werkzeug/2.2.2 Python/3.10.5
<!doctype html> <html lang=en> <title>404 Not Found</title> <h1>Not Found</h1> <p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
修改tutorweb/api/errors.py,设置返回JSON错误信息
1 2 3 4 5 6 7 8 9 10 11 12
from tutorweb import db from tutorweb.api import bp ...
@bp.route('/users/<int:id>',methods=['PUT']) defupdate_user(id): #修改一个用户 user=User.query.get_or_404(id) data=request.get_json() ifnot data: return bad_request('You must post JSON data.')
message={} if'username'in data andnot data.get('username', None): message['username']='Please provide a valid username.' pattern='^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$' if'email'in data andnot re.match(pattern, data.get('email', None)): message['email']='Please provide a valid email address.' if'username'in data and data['username'] != user.username and \ User.query.filter_by(username=data['username']).first(): message['username']='Please use a different username.' if'email'in data and data['email'] != user.email and \ User.query.filter_by(email=data['email']).first(): message['email']='Please use a different email address.'
if message: return bad_request(message) user.from_dict(data,new_user=False) db.session.commit() return jsonify(user.to_dict())
终端测试如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
(venv) PS C:\Users\Administrator\Desktop\code_learn\flask_exercise\tutorproject\back-end> http PUT http://localhost:5000/api/users/5 email=madman@gmail.com
HTTP/1.1 200 OK Access-Control-Allow-Origin: * Connection: close Content-Length: 82 Content-Type: application/json Date: Mon, 24 Oct 2022 05:16:38 GMT Server: Werkzeug/2.2.2 Python/3.10.5
@staticmethod defcheck_token(token): user = User.query.filter_by(token=token).first() if user isNoneor user.token_expiration < datetime.utcnow(): returnNone return user
创建数据库迁移脚本并应用:
1 2
(venv) PS C:\Users\Administrator\Desktop\code_learn\flask_exercise\tutorproject\back-end>flask db migrate -m "user add tokens" (venv) PS C:\Users\Administrator\Desktop\code_learn\flask_exercise\tutorproject\back-end>flask db upgrade
from flask import g from flask_httpauth import HTTPBasicAuth,HTTPTokenAuth from tutorweb.models import User from tutorweb.api.errors import error_response
basic_auth=HTTPBasicAuth()
@basic_auth.verify_password defverify_password(username,password): #用于检查用户提供的用户名和密码 user=User.query.filter_by(username=username).first() if user isNone: returnFalse g.current_user=user return user.check_password(password)