码迷,mamicode.com
首页 > 其他好文 > 详细

Flask

时间:2018-10-03 00:22:10      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:pre   ror   test   flask   object   登录   poi   列表   template   

URL和视图

典型的综合code:

from flask import Flask, redirect, url_for
import config        #config.py
app = Flask(__name__)
app.config.from_object(config)

@app.route(‘/user‘, methods=[‘GET‘, ‘POST‘])
def user():
  if request.method == ‘GET‘:
    #返回用户列表
  if request.method == ‘POST‘:
    #创建新用户啊
    
#any可指定多个路径,path可接受‘/‘字符串 @app.route(
‘/<any(blog, diary):url_path/<path:test_path>/‘)   def index(url_path, test_path):   #url: /blog/path1/path2/path3/?param=1 print ‘test_path‘  #path1/path2/path3/ param = request.args.get(‘param‘) #1 if url_path == ‘blog‘: return ‘博客板块‘ else if url_path == ‘diary‘: return ‘日志板块‘ else: return redirect(url_for(‘mylist‘, page=1, count=2)) #/list/1/?count=2 @app.route(‘/list/<page>/‘) def my_list(page): return ‘my_list‘

#类视图,继承 view.View, 实现 dispatch_request 方法,该方法接收对应url的请求后返回Response或其子类对象,也可返回 字符串或元组。
#此时url和视图类的映射通过app.add_url_role(url_rule,view_func) 完成。
class UserView(views.MethodView):
  def __render( self, error=None):
    return render_template( ‘user.html‘, error=error)
  
  def get(self, error=None):
    return self.__render()

  def post( self, error=None):
    username = request.form.get(‘username‘)
    password = request.form.get(‘password‘)
    if judge(username, password):
      return ‘登录成功‘
    else:
      return self.__render(‘error=用户名或密码错误‘)

app.add_url_role(‘/user/‘, endpoint=‘user‘, view_func=UserView.as_view(‘user‘))
 

 

config.py:

DEBUG = True

 

Flask

标签:pre   ror   test   flask   object   登录   poi   列表   template   

原文地址:https://www.cnblogs.com/brendy/p/9673473.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!