app.route
和app.add_url_rule
app.add_url_rule
app.add_url_rule('/list/',endpoint='myweb',view_func=my_list)
这个方法是用来添加url
与视图函数
的映射。若是没有填写endpoint
那么会默认使用view_func
的名字来做为endpoint
。
所以在使用url_for
的时候,就要看在映射的时候有没有传递endpoint
参数,若是传递了,那么就使用endpoint
指定的字符串。
付过没有使用的话就使用view_func
定义的名字。css
app.route(rule,**options)
装饰器这个装饰器的底层就是用add_url_rule
来实现url与视图函数映射的。html
from flask import Flask,url_for app = Flask(__name__) app.config.update({ 'DEBUG':True, 'TEMPLATES_AUTO_RELOAD':True }) @app.route('/',endpoint='index') def hello_world(): print(url_for('myweb')) return 'Hello World!' def my_list(): return 'list page!' app.add_url_rule('/list/',endpoint='myweb',view_func=my_list) #请求上下文的定义,结合url_for with app.test_request_context(): print(url_for('index')) if __name__ == '__main__': app.run()
以前咱们接触的视图都是函数,因此通常简称视图函数。
其实视图也能够基于类来实现,类视图的好处是支持继承,可是类视图不能跟函数视图同样,
写完类视图还须要经过app.add_url_rule(url_rule,view_func)
来进行注册。如下将对两种类视图进行讲解python
flask.views.View
dispatch_request
方法,之后请求过来之后,会执行这个方法。这个方法的返回值就至关因而以前的函数视图同样,也必须返回Request
或者子类的对象(字符串或者元组)。app.add_url_rule(rule,endpoint,view_func)
来作url映射。view_func
这个参数,要使用as_view
这个方法来转换web
endpoint
,那么在使用url_for
反转的时候,就要使用endpoint
指定的那个值,若是没有指定那个值,就使用as_view
中指定的视图名字来做为反转。from flask import Flask,views,url_for app = Flask(__name__) class ListView(views.View): def dispatch_request(self): return 'list view' #app.add_url_rule('/list/',endpoint='list',view_func=ListView.as_view('list')) app.add_url_rule('/list/',view_func=ListView.as_view('list')) with app.test_request_context(): print(url_for('list')) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run(debug=True)
from flask import Flask,url_for,views,jsonify,render_template app = Flask(__name__) app.config.update({ 'DEBUG':True, 'TEMPLATES_AUTO_RELOAD':True }) #自定义封装,返回json数据 class JSONView(views.View): def get_data(self): raise NotImplementedError def dispatch_request(self): return jsonify(self.get_data()) class ListView(JSONView): def get_data(self): return { 'username':'wanghui', 'password':123456, } app.add_url_rule('/list/',endpoint='my_list',view_func=ListView.as_view('list')) #有几个视图,须要返回相同的变量(广告页面) class ADSView(views.View): def __init__(self): super(ADSView, self).__init__() self.context = { 'ads':"今年过节不收礼,收礼只收脑白金" } class RegistView(ADSView): def dispatch_request(self): self.context.update({'username':'abcd'}) return render_template('register.html',**self.context) class LoginView(ADSView): def dispatch_request(self): return render_template('login.html',**self.context) # class LoginView(views.View): # def dispatch_request(self): # return render_template('login.html',ads="今年过节不收礼,收礼只收脑白金") # class RegistView(views.View): # def dispatch_request(self): # return render_template('register.html',ads="今年过节不收礼,收礼只收脑白金") app.add_url_rule('/login/',view_func=LoginView.as_view('login')) app.add_url_rule('/regist/',view_func=RegistView.as_view('regist')) @app.route('/') def hello(): return "heello" if __name__ == '__main__': app.run()
request.method == 'POST'
来搞了。from flask import Flask,views,render_template,request app = Flask(__name__) class LoginView(views.MethodView): def __render(self,error=None): return render_template('login.html',error=error) def get(self,error=None): # return render_template('login.html',error=error) return self.__render() def post(self): username = request.form.get('username') password = request.form.get('password') if username == 'wanghui' and password == '111111': return 'login success' else: # return render_template('login.html',error="username or password error,retry!") # return self.get(error="username or password error,retry!") return self.__render(error="username or password error,retry!") app.add_url_rule('/login/',view_func=LoginView.as_view('login')) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run(debug=True,port=9090)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>login</title> </head> <body> <form action="" method="post"> <table> <tr> <td>用户名</td> <td><input type="text" name="username"></td> </tr> <tr> <td>密码</td> <td><input type="password" name="password"></td> </tr> <tr> <td></td> <td><input type="submit" value="当即登录"></td> </tr> </table> {% if error %} <p style="color: red;">{{ error }}</p> {% endif %} </form> </body> </html>
两种类型的装饰器json
- 若是使用的是函数视图, 那么定义的装饰器必须放在
app.route
下面,不然起不到任何做用
decorators
类属性,里面装的就是全部的装饰器from flask import Flask,request,views from functools import wraps app = Flask(__name__) #定义装饰器 def login_required(func): @wraps(func) def wrapper(*args,**kwargs): username = request.args.get('username') if username and username == 'wanghui': return func(*args,**kwargs) else: return "请先登陆" return wrapper @app.route('/settings/') @login_required def settings(): return '这是设置页面' #这样请求就行http://127.0.0.1:9091/settings/?username=wanghui #类视图添加装饰器 class ProfileView(views.View): decorators = [login_required] def dispatch_request(self): return "这是我的中心" app.add_url_rule('/profile/',view_func=ProfileView.as_view('profile'))
将大型项目分层解耦,实现模块化,结构更加清晰。能够将相同的模块放在同一个蓝图下,同一个文件夹中。方便管理。
from flask import Blueprint user_bp = Blueprint('user',__name__) #至关因而定义`app = Flask(__name__)`
from blueprints.user import user_bp app.regist_blueprint(user_bp) #实现注册蓝图
URL
的时候有个前缀,那么能够在定义蓝图的时候加上url_prefix
from flask import Blueprint user_bp = Blueprint('user',__name__,url_prefix='/user') # 特别注意斜杠
蓝图模板文件查找:flask
templates
文件夹中存在对应的模板文件,就能够直接使用templates
文件夹中存在相应的模板文件,那么就在定义蓝图的指定路径中查找,能够设置相对路径,就要在蓝图文件相同路径下的文件夹。
from flask import Blueprint,render_template news_bp = Blueprint('news',__name__,url_prefix='/news',template_folder='news') @news_bp.route('/list/') def news_list(): return render_template('news_list.html')
蓝图中的静态文件查找:app
url_for('static')
,那么只会在app指定的静态文件夹目录下查找静态文件url_for('news.static')
,那么会到蓝图指定的static_folder
下查找静态文件。url_for
到蓝图中的视图函数的时候,要反转蓝图中的视图函数为url,那么就用该在使用url_for
的时候使用url_for('news.news_list')
否则就找不到这个endpoint。subdomain
来指定这个子域名from flask import Blueprint cms_bp = Blueprint('cms',__name__,subdomain='cms')
app.config['SERVER_NAME']='baidu.com'
来指定跟域名app.config['SERVER_NAME'] = 'crop.com:9099'
127.0.0.1 crop.com 127.0.0.1 cms.crop.com
5.访问dom
cms.crop.com:9099
blue_print_e ├── blue_print_e.py ├── blueprints │ ├── bok.py │ ├── cms.py │ ├── movie.py │ ├── news_css │ │ └── news_list.css │ ├── news.py │ ├── news_tmp │ │ └── news_list.html │ └── user.py ├── static │ └── news_list.css └── templates ├── index.html └── news_list.html
blue_print_e.py
from flask import Flask,url_for,render_template from blueprints.user import user_bp from blueprints.news import news_bp from blueprints.cms import cms_bp app = Flask(__name__) app.config['SERVER_NAME'] = 'crop.com:9099' app.register_blueprint(user_bp) app.register_blueprint(news_bp) app.register_blueprint(cms_bp) # ip地址不能有子域名 @app.route('/') def hello_world(): print(url_for('news_tmp.news_list')) #使用蓝图名字.视图函数的名字 return render_template('index.html') if __name__ == '__main__': app.run(debug=True,port=9099)
blueprints/news.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Blueprint,render_template,url_for news_bp = Blueprint('news_tmp',__name__,url_prefix='/news_tmp',template_folder='news_tmp',static_folder='news_css') @news_bp.route('/list/') def news_list(): print(url_for('news.news_detail')) return render_template('news_list.html') @news_bp.route('/detail') def news_detail(): return "详情页面"
blueprints/user.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Blueprint user_bp = Blueprint('user',__name__,url_prefix='/user') @user_bp.route('/profile/') def profile(): return "我的中心" @user_bp.route('/settings/') def settings(): return "设置页面"
blueprint/cms.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Blueprint cms_bp = Blueprint('cms',__name__,subdomain='cms') @cms_bp.route('/') def index(): return 'cms index'
blueprints/news_css/
body { color: fuchsia; font-size: 90px; background: red; }