Flask基礎教程
1. 簡介
Flask是一個基於Python開發並且依賴jinja2模板和Werkzeug WSGI服務的一個微型框架,對於Werkzeug本質是Socket服務端,其用於接收http請求並對請求進行預處理,然后觸發Flask框架,開發人員基於Flask框架提供的功能對請求進行相應的處理,並返回給用戶,如果要返回給用戶復雜的內容時,需要借助jinja2模板來實現對模板的處理,即:將模板和數據進行渲染,將渲染后的字符串返回給用戶瀏覽器。
“微”(micro) 並不表示你需要把整個 Web 應用塞進單個 Python 文件(雖然確實可以 ),也不意味着 Flask 在功能上有所欠缺。微框架中的“微”意味着 Flask 旨在保持核心簡單而易於擴展。Flask 不會替你做出太多決策——比如使用何種數據庫。而那些 Flask 所選擇的——比如使用何種模板引擎——則很容易替換。除此之外的一切都由可由你掌握。如此,Flask 可以與您珠聯璧合。
默認情況下,Flask 不包含數據庫抽象層、表單驗證,或是其它任何已有多種庫可以勝任的功能。然而,Flask 支持用擴展來給應用添加這些功能,如同是 Flask 本身實現的一樣。眾多的擴展提供了數據庫集成、表單驗證、上傳處理、各種各樣的開放認證技術等功能。Flask 也許是“微小”的,但它已准備好在需求繁雜的生產環境中投入使用。
2. 基本使用
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()
3. 配置文件
flask中的配置文件是一個flask.config.Config對象(繼承字典),默認配置為:
{ 'DEBUG':False, 'TESTING':False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': None, 'PERMANENT_SESSION_LIFETIME': timedelta(days=31), 'USE_X_SENDFILE': False, 'LOGGER_NAME': None, 'LOGGER_HANDLER_POLICY': 'always', 'SERVER_NAME': None, 'APPLICATION_ROOT': None, 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12), 'TRAP_BAD_REQUEST_ERRORS': False, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': True, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, }
方式一:
app.config['DEBUG'] = True
PS: 由於Config對象本質上是字典,所以還可以使用app.config.update(...)
方式二:app.config.from_pyfile("python文件名稱")
settings.py
DEBUG = True
app.config.from_pyfile("settings.py") app.config.from_envvar("環境變量名稱")
環境變量的值為python文件名稱名稱,內部調用from_pyfile方法
app.config.from_json("json文件名稱")
JSON文件名稱,必須是json格式,因為內部會執行json.loads
app.config.from_mapping({'DEBUG':True})
字典格式
app.config.from_object("python類或類的路徑") app.config.from_object('pro_flask.settings.TestingConfig')
settings.py
class Config(object): DEBUG = False TESTING = False DATABASE_URI = 'sqlite://:memory:'
class ProductionConfig(Config): DATABASE_URI = 'mysql://user@localhost/foo'
class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True
PS: 從sys.path中已經存在路徑開始寫
PS: settings.py文件默認路徑要放在程序root_path目錄,如果instance_relative_config 為True,則就是instance_path目錄
4. 路由系統
1 @app.route('/user/<username>')
3 @app.route('/post/<int:post_id>')
5 @app.route('/post/<float:post_id>')
7 @app.route('/post/<path:path>')
9 @app.route('/login', methods=['GET', 'POST'])
常用路由系統有以上五種,所有的路由系統都是基於一下對應關系來處理:
DEFAULT_CONVERTERS = { 'default':UnicodeConverter, 'string':UnicodeConverter, 'any':AnyConverter, 'path':PathConverter, 'int':IntegerConverter, 'float':FloatConverter, 'uuid':UUIDConverter, }
4.1 注冊路由原理
def auth(func): def inner(*args, **kwargs): print('before') result = func(*args, **kwargs) print('after') return result return inner @app.route('/index.html', methods=['GET', 'POST'], endpoint='index') @auth def index(): return 'Index'
或
def index(): return "Index" self.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"])
or
app.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"]) app.view_functions['index'] = index
或
def auth(func): def inner(*args, **kwargs): print('before') result = func(*args, **kwargs) print('after') return result return inner class IndexView(views.View): methods = ['GET'] decorators = [auth, ] def dispatch_request(self): print('Index') return 'Index!' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint
或
class IndexView(views.MethodView): methods = ['GET'] decorators = [auth, ] def get(self): return 'Index.GET'
def post(self): return 'Index.POST' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint
@app.route和app.add_url_rule參數:
1 rule,URL規則 3 view_func, 視圖函數名稱 5 defaults=None, 默認值,當URL中無參數,函數需要參數時,使用 defaults={'k':'v'}為函數提供參數 7 endpoint=None, 名稱,用於反向生成URL,即: url_for('名稱') 9 methods=None, 允許的請求方式,如:["GET","POST"]
strict_slashes=None,對URL最后的 / 符號是否嚴格要求,
如:
1 @app.route('/index',strict_slashes=False),
訪問 http://www.xx.com/index/ 或 http://www.xx.com/index均可
1 @app.route('/index',strict_slashes=True)
僅訪問 http://www.xx.com/index
redirect_to=None, 重定向到指定地址
如:
1 @app.route('/index/<int:nid>', redirect_to='/home/<nid>')
或
def func(adapter, nid): return "/home/888" @app.route('/index/<int:nid>', redirect_to=func)
subdomain=None, 子域名訪問
from flask import Flask, views, url_for app = Flask(import_name=__name__) app.config['SERVER_NAME'] = 'wupeiqi.com:5000'
@app.route("/", subdomain="admin") def static_index(): """
Flask supports static subdomains This is available at static.your-domain.tld
""" return "static.your-domain.tld" @app.route("/dynamic", subdomain="<username>") def username_index(username): """
Dynamic subdomains are also supported Try going to user1.your-domain.tld/dynamic
""" return username + ".your-domain.tld" if __name__ == '__main__': app.run()
4.1 自定制正則路由匹配
from flask import Flask, views, url_for from werkzeug.routing import BaseConverter app = Flask(import_name=__name__) class RegexConverter(BaseConverter): """ 自定義URL匹配正則表達式 """ def __init__(self, map, regex): super(RegexConverter, self).__init__(map) self.regex = regex def to_python(self, value): """ 路由匹配時,匹配成功后傳遞給視圖函數中參數的值 :param value: :return: """ return int(value) def to_url(self, value): """ 使用url_for反向生成URL時,傳遞的參數經過該方法處理,返回的值用於生成 URL中的參數 :param value: :return: """ val = super(RegexConverter, self).to_url(value) return val # 添加到flask中 app.url_map.converters['regex'] = RegexConverter @app.route('/index/<regex("\d+"):nid>') def index(nid): print(url_for('index', nid='888')) return 'Index' if __name__ == '__main__': app.run()
5. 模板
1、模板的使用
Flask使用的是Jinja2模板,所以其語法和Django無差別
2、自定義模板方法
Flask中自定義模板方法的方式和Bottle相似,創建一個函數並通過參數的形式傳入 render_template,如:
html:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <h1>自定義函數</h1> {{ww()|safe}} </body> </html>
run.py:
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask,render_template
app = Flask(__name__) def wupeiqi(): return '<h1>Wupeiqi</h1>'
@app.route('/login', methods=['GET', 'POST']) def login(): return render_template('login.html', ww=wupeiqi)
app.run()
其他:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% macro input(name, type='text', value='') %} <input type="{{ type }}" name="{{ name }}" value="{{ value }}"> {% endmacro %} {{ input('n1') }} {% include 'tp.html' %} <h1>asdf{{ v.k1}}</h1> </body> </html>
6. 請求和響應
from flask import request from flask import render_template from flask import redirect from flask import make_response app = Flask(__name__) @app.route('/login.html', methods=['GET', "POST"]) def login(): # 請求相關信息 ===================================================================== # request.method # request.args # request.form # request.values # request.cookies # request.headers # request.path # request.full_path # request.script_root # request.url # request.base_url # request.url_root # request.host_url # request.host # request.files # obj = request.files['the_file_name'] # obj.save('/var/www/uploads/' + secure_filename(f.filename)) # 響應相關信息 =================================================================== # return "字符串" # return render_template('html模板路徑',**{}) # return redirect('/index.html') # response = make_response(render_template('index.html')) # response是flask.wrappers.Response類型 # response.delete_cookie('key') # response.set_cookie('key', 'value') # response.headers['X-Something'] = 'A value' # return response return "內容" if __name__ == '__main__': app.run()
7. Session
除請求對象之外,還有一個 session 對象。它允許你在不同請求間存儲特定用戶的信息。 它是在 Cookies 的基礎上實現的,並且對 Cookies 進行密鑰簽名要使用會話,你需要設 置一個密鑰。
1 設置:session['username'] = 'xxx' 3 刪除:session.pop('username', None)
7.1 基本使用:
from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) @app.route('/') def index(): if 'username' in session: return 'Logged in as %s' % escape(session['username']) return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return ''' <form action="" method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index')) # set the secret key. keep this really secret: app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
7.2 自定義Session
1 pip3 install Flask-Session
run.py:
from flask import Flask from flask import session from pro_flask.utils.session import MySessionInterface app = Flask(__name__) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' app.session_interface = MySessionInterface() @app.route('/login.html', methods=['GET', "POST"]) def login(): print(session) session['user1'] = 'alex' session['user2'] = 'alex' del session['user2'] return "內容" if __name__ == '__main__': app.run()
session.py:
import uuid import json import redis from flask.sessions import SessionInterface from flask.sessions import SessionMixin from itsdangerous import Signer, BadSignature, want_bytes class MySession(dict, SessionMixin): def __init__(self, initial=None, sid=None): self.sid = sid self.initial = initial super(MySession, self).__init__(initial or ()) def __setitem__(self, key, value): super(MySession, self).__setitem__(key, value) def __getitem__(self, item): return super(MySession, self).__getitem__(item) def __delitem__(self, key): super(MySession, self).__delitem__(key) class MySessionInterface(SessionInterface): session_class = MySession container = {} def __init__(self): self.redis = redis.Redis() def _generate_sid(self): return str(uuid.uuid4()) def _get_signer(self, app): if not app.secret_key: return None return Signer(app.secret_key, salt='flask-session', key_derivation='hmac') def open_session(self, app, request): """ 程序剛啟動時執行,需要返回一個session對象 """ sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid) signer = self._get_signer(app) try: sid_as_bytes = signer.unsign(sid) sid = sid_as_bytes.decode() except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid) # session保存在redis中 # val = self.redis.get(sid) # session保存在內存中 val = self.container.get(sid) if val is not None: try: data = json.loads(val) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid) return self.session_class(sid=sid) def save_session(self, app, session, response): """ 程序結束前執行,可以保存session中所有的值 如: 保存到resit 寫入到用戶cookie """ domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = json.dumps(dict(session)) # session保存在redis中 # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime) # session保存在內存中 self.container.setdefault(session.sid, val) session_id = self._get_signer(app).sign(want_bytes(session.sid)) response.set_cookie(app.session_cookie_name, session_id,expires=expires, httponly=httponly,domain=domain, path=path, secure=secure)
7.3 第三方Session
#!/usr/bin/env python # -*- coding:utf-8 -*- """ pip3 install redis pip3 install flask-session """ from flask import Flask, session, redirect from flask.ext.session import Session app = Flask(__name__) app.debug = True app.secret_key = 'asdfasdfasd' app.config['SESSION_TYPE'] = 'redis' from redis import Redis app.config['SESSION_REDIS'] = Redis(host='192.168.0.94',port='6379') Session(app) @app.route('/login') def login(): session['username'] = 'alex' return redirect('/index') @app.route('/index') def index(): name = session['username'] return name if __name__ == '__main__': app.run()
8. 藍圖
藍圖用於為應用提供目錄划分:
8.1 小型應用程序:示例
目錄結構:

run.py:詳細代碼:
from pro_flask import app if __name__ == '__main__': app.run()
__init__.py:
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask from .views.account import account from .views.blog import blog from .views.user import user app=Flask(__name__,template_folder='templates',static_folder='statics',static_url_path='/static') app.register_blueprint(account) app.register_blueprint(blog) app.register_blueprint(user)
Account.py:
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Blueprint from flask import render_template from flask import request account = Blueprint('account', __name__) @account.route('/login.html', methods=['GET', "POST"]) def login(): return render_template('login.html')
Blog.py:
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Blueprint blog = Blueprint('blog', __name__)
User.py
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Blueprint user = Blueprint('user', __name__)
Login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用戶登錄</h1> <form method="POST"> <input type="text" name="user"/> <input type="submit" value="提交"/> </form> <img src="/static/code.png"> <img src="{{ url_for('static',filename='code.png') }}"> </body> </html>
8.2 大型應用程序:示例
目錄結構:

詳細代碼:
Run.py:
from pro_flask import app if __name__ == '__main__': app.run()
__init__.py:
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask from .admin import admin from .web import web app = Flask(__name__) app.debug = True app.register_blueprint(admin, url_prefix='/admin') app.register_blueprint(web)
Admin/__init__.py:
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Blueprint admin = Blueprint('admin',__name__,template_folder='templates',static_folder='static') from . import views
Admin/views.py:
#!/usr/bin/env python # -*- coding:utf-8 -*- from . import admin @admin.route('/index') def index(): return 'Admin.Index'
Web/__init.py:
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Blueprint web = Blueprint('web',__name__,template_folder='templates',static_folder='static') from . import views
Web/views.py:
#!/usr/bin/env python # -*- coding:utf-8 -*- from . import web @web.route('/index') def index(): return 'Web.Index'
8.3 其他:
藍圖URL前綴:xxx = Blueprint('account', __name__,url_prefix='/xxx')
藍圖子域名:xxx = Blueprint('account', __name__,subdomain='admin')
# 前提需要給配置SERVER_NAME: app.config['SERVER_NAME'] = 'wupeiqi.com:5000'
# 訪問時:admin.wupeiqi.com:5000/login.html
9. Message
message是一個基於Session實現的用於保存數據的集合,其特點是:使用一次就刪除。
from flask import Flask, flash, redirect, render_template, request, get_flashed_messages app = Flask(__name__) app.secret_key = 'some_secret' @app.route('/') def index1(): messages = get_flashed_messages() print(messages) return "Index1" @app.route('/set') def index2(): v = request.args.get('p') flash(v) return 'ok' if __name__ == "__main__": app.run()
10. 中間件
from flask import Flask, flash, redirect, render_template, request app = Flask(__name__) app.secret_key = 'some_secret'
@app.route('/') def index1(): return render_template('index.html') @app.route('/set') def index2(): v = request.args.get('p') flash(v) return 'ok' class MiddleWare: def __init__(self,wsgi_app): self.wsgi_app = wsgi_app
def __call__(self, *args, **kwargs): return self.wsgi_app(*args, **kwargs) if __name__ == "__main__": app.wsgi_app = MiddleWare(app.wsgi_app) app.run(port=9999)
11. 請求擴展
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask, Request, render_template app = Flask(__name__, template_folder='templates') app.debug = True @app.before_first_request def before_first_request1(): print('before_first_request1') @app.before_first_request def before_first_request2(): print('before_first_request2') @app.before_request def before_request1(): Request.nnn = 123 print('before_request1') @app.before_request def before_request2(): print('before_request2') @app.after_request def after_request1(response): print('before_request1', response) return response @app.after_request def after_request2(response): print('before_request2', response) return response @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 @app.template_global() def sb(a1, a2): return a1 + a2 @app.template_filter() def db(a1, a2, a3): return a1 + a2 + a3 @app.route('/') def hello_world(): return render_template('hello.html') if __name__ == '__main__': app.run()
調用方式:{{sb(1,2)}} {{ 1|db(2,3)}}
12. Flask插件
12.1 WTForms
簡介:
WTForms是一個支持多個web框架的form組件,主要用於對用戶請求數據進行驗證。
簡單使用:
安裝:pip install wtforms
demo1(用戶登錄)
app.py:from flask import Flask, render_template, request, redirect
from wtforms import Form from wtforms.fields import simple from wtforms import validators from wtforms import widgets app = Flask(__name__, template_folder='templates') app.debug = True class LoginForm(Form): name = simple.StringField(label='用戶名', validators=[ validators.DataRequired(message='用戶名不能為空.'), validators.Length(min=6, max=18, message='用戶名長度必須大於%(min)d且小於%(max)d') ], widget=widgets.TextInput(), render_kw={'class': 'form-control'} ) pwd = simple.PasswordField( label='密碼', validators=[ validators.DataRequired(message='密碼不能為空.'), validators.Length(min=8, message='用戶名長度必須大於%(min)d'), validators.Regexp(regex="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Z a-z\d$@$!%*?&]{8,}",message='密碼至少8個字符,至少1個大寫字母,1個 小寫字母,1個數字和1個特殊字符') ], widget=widgets.PasswordInput(), render_kw={'class': 'form-control'} ) @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': form = LoginForm() return render_template('login.html', form=form) else: form = LoginForm(formdata=request.form) if form.validate(): print('用戶提交數據通過格式驗證,提交的值為:', form.data) else: print(form.errors) return render_template('login.html', form=form)
if __name__ == '__main__': app.run()
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>登錄</h1> <form method="post"> <!--<input type="text" name="name">--> <p>{{form.name.label}} {{form.name}} {{form.name.errors[0] }}</p> <!--<input type="password" name="pwd">--> <p>{{form.pwd.label}} {{form.pwd}} {{form.pwd.errors[0] }}</p> <input type="submit" value="提交"> </form> </body> </html>
demo2(用戶注冊):
app.py
from flask import Flask, render_template, request, redirect from wtforms import Form from wtforms.fields import core from wtforms.fields import html5 from wtforms.fields import simple from wtforms import validators from wtforms import widgets app = Flask(__name__, template_folder='templates') app.debug = True class RegisterForm(Form): name = simple.StringField( label='用戶名', validators=[ validators.DataRequired() ], widget=widgets.TextInput(), render_kw={'class': 'form-control'}, default='alex' ) pwd = simple.PasswordField( label='密碼', validators=[ validators.DataRequired(message='密碼不能為空.') ], widget=widgets.PasswordInput(), render_kw={'class': 'form-control'} ) pwd_confirm = simple.PasswordField( label='重復密碼', validators=[ validators.DataRequired(message='重復密碼不能為空.'), validators.EqualTo('pwd', message="兩次密碼輸入不一致") ], widget=widgets.PasswordInput(), render_kw={'class': 'form-control'} ) email = html5.EmailField( label='郵箱', validators=[ validators.DataRequired(message='郵箱不能為空.'), validators.Email(message='郵箱格式錯誤') ], widget=widgets.TextInput(input_type='email'), render_kw={'class': 'form-control'} ) gender = core.RadioField( label='性別', choices=((1, '男'),(2, '女'),),
coerce=int ) city = core.SelectField( label='城市', choices=(('bj', '北京'),('sh', '上海'),) ) hobby = core.SelectMultipleField( label='愛好', choices=((1, '籃球'),(2, '足球'),), coerce=int )
favor = core.SelectMultipleField( label='喜好', choices=((1, '籃球'),(2, '足球'),), widget=widgets.ListWidget(prefix_label=False), option_widget=widgets.CheckboxInput(), coerce=int, default=[1, 2] )
def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.favor.choices = ((1, '籃球'), (2, '足球'), (3, '羽毛球')) def validate_pwd_confirm(self, field): """ 自定義pwd_confirm字段規則,例:與pwd字段是否一致 :param field: :return: """ # 最開始初始化時,self.data中已經有所有的值 if field.data != self.data['pwd']: # raise validators.ValidationError("密碼不一致") # 繼續后續驗證 raise validators.StopValidation("密碼不一致") # 不再繼續后續驗證 @app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'GET': form = RegisterForm(data={'gender': 1}) return render_template('register.html', form=form) else: form = RegisterForm(formdata=request.form) if form.validate(): print('用戶提交數據通過格式驗證,提交的值為:', form.data) else: print(form.errors) return render_template('register.html', form=form) if __name__ == '__main__': app.run()
register.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用戶注冊</h1> <form method="post" novalidate style="padding:0 50px"> {% for item in form %} <p>{{item.label}}: {{item}} {{item.errors[0] }}</p> {% endfor %} <input type="submit" value="提交"> </form> </body> </html>
如何實現:
源碼流程:
1 解釋:metaclass 3 實例:form = LoginForm 5 驗證:form.validate()
12.2 SQLAchemy
SQLAlchemy項目基礎實例
項目結構:
__init__.py:
from flask import Flask from flask_sqlalchemy import SQLAlchemy from .views.admin import admin from .views.shop import shop db = SQLAlchemy() from .models import * def create_app(): app = Flask(__name__, template_folder='templates', static_folder='statics', static_url_path='/static') # 導入配置文件(以類的形式導入) app.config.from_object("settings.TsetSesstings") # 將db注冊到app中(在內部讀取配置文件) db.init_app(app) #注冊藍圖 app.register_blueprint(admin) app.register_blueprint(shop) return app
run.py:
# 程序入口from flask_app import create_app app = create_app() if __name__ == '__main__': app.run()
settings.py:
# 這是配置文件 # 測試配置 class TsetSesstings(): DEBUG = True TESTING = True SECRET_KEY = "djcishcnieodkscj9codscojsojcd0ojc" ''' 數據庫連接配置 SQLALCHEMY_DATABASE_URI', 'sqlite:///:memory:' SQLALCHEMY_BINDS', None SQLALCHEMY_NATIVE_UNICODE', None SQLALCHEMY_ECHO', False SQLALCHEMY_RECORD_QUERIES', None SQLALCHEMY_POOL_SIZE', None SQLALCHEMY_POOL_TIMEOUT', None SQLALCHEMY_POOL_RECYCLE', None SQLALCHEMY_MAX_OVERFLOW', None SQLALCHEMY_COMMIT_ON_TEARDOWN', False ''' SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:密碼@localhost:3306/數據庫名' SQLALCHEMY_POOL_SIZE = 5 SQLALCHEMY_POOL_TIMEOUT = 30 SQLALCHEMY_POOL_RECYCLE = -1 # 追蹤對象的修改並且發送信號 SQLALCHEMY_TRACK_MODIFICATIONS = False # 正式配置 class FormalSettings(): DEBUG = False TESTING = False SECRET_KEY = "xfsec@admin!2019(shuijizifuchuan)" #數據庫連接 SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:密碼@localhost:3306/數據庫名' SQLALCHEMY_POOL_SIZE = 5 SQLALCHEMY_POOL_TIMEOUT = 30 SQLALCHEMY_POOL_RECYCLE = -1 # 追蹤對象的修改並且發送信號 SQLALCHEMY_TRACK_MODIFICATIONS = False
models.py:
from . import db class Users1(db.Model): __tablename__ = "users" id = db.Column(db.Integer,primary_key=True) username = db.Column(db.String(50),nullable=False,unique=True) email = db.Column(db.String(150), nullable=False, unique=True) def __repr__(self): return "<Users %r>" %self.username
crcate_tables.py :
# 這是一個創建數據庫表的腳本 from flask_app import db from flask_app import create_app app = create_app() with app.app_context(): db.create_all()
admin.py :
from flask import Blueprint from flask import render_template from flask import request # 創建app應用 # url_prefix : 路由拼接 # template_folder : 模板路徑 admin= Blueprint('admin', __name__, url_prefix='/admin', template_folder='templates') # 每次請求進來時的操作 @admin.before_request def process_request(*args, **kwargs): ''' 判斷用戶是否登陸 ''' if request.path == "/admin_dingding_xfsec/login": print("登錄頁面不需要登陸!!!") return None else: print("后台每次請求進來時都會執行這個函數") #每次請求結束時的操作(必須加return 否則會報錯!!!) @admin.after_request def process_response(response): print("后台每次請求結束后都會執行這個函數") return response @admin.route('/login', methods=['GET', "POST"]) def login(): if request.method == "GET": return "前端登錄頁面!!!" else: pass @admin.route('/index', methods=['GET', "POST"]) def index(): if request.method == "GET": return "前端首頁!!!" else: pass
shop.py:
from flask import Blueprintfrom flask import render_templatefrom flask import request ''' 前端管理函數處理 使用藍圖 創建藍圖實例 創建路由 函數處理
''' shop = Blueprint('shop', __name__, template_folder='templates') # 每次請求進來時的操作 @shop.before_requestdef process_request(*args, **kwargs): print("前端每次請求進來時都會執行這個函數") # 每次請求結束時的操作(必須加return 否則會報錯!!!) @shop.after_requestdef process_response(response): print("前端每次請求結束后都會執行這個函數") return response @shop.route('/login', methods=['GET', "POST"])def login(): if request.method == "GET": return "前端登錄頁面!!!" else: pass @shop.route('/index', methods=['GET', "POST"])def index(): if request.method == "GET": return "前端首頁!!!" else: pass
等... http://flask.pocoo.org/extensions/
