Flask

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
原文地址:https://www.cnblogs.com/brendy/p/9673473.html