python flask路由重要知识点

  • 来源:新网
  • 更新日期:2018-04-18

摘要:#coding utf8 # Flask初始化 from flask import Flask ,request ,current_app ,app ,make_response,render_template ,redirect ,abort ,session ,jsonify app = Flask(__name__) # jsonify返回的json串支持中文支持

#coding utf8 # Flask初始化 from flask import Flask ,request ,current_app ,app ,make_response,render_template ,redirect ,abort ,session ,jsonify app = Flask(__name__) # jsonify返回的json串支持中文支持

1-16092Q15623J4.gif

app.config[\'JSON_AS_ASCII\'] = False # 修饰器注册路由app.route @app.route("/") def index(): result = { \'status\': "200", \'data\': \'Hello, world!\', } return jsonify(result) # 通过add_url_rule函数注册路由 def index2(): return \'index2\' app.add_url_rule(\'/index2\',view_func=index2) # 渲染模板,默认保存在templates目录下 @app.route("/tem") def tem(): return render_template(\'/tem.html\',message=\'Bad username or password\', title="title") # 指定传输方式 @app.route(\'/user\',methods=[\'POST\',\'GET\']) def v_users(): if request.method == \'GET\': return ... # 返回用户列表 if request.method == \'POST\' return ... #创建新用户 @app.route("/name/<name>") def name(name): # return name # return "<h1>"+name+"</h1>" # if not name: # abort(404) return "<h1> %s</h1>" %len(name) @app.route("/req/") def req(): users_agent=request.headers.get(\'User-Agent\') Host=request.headers.get(\'Host\') appname=current_app.name return users_agent+""+Host+""+appname # 调试信息 @app.route("/debug/") def debug(): # app.logger.debug(\'A value for debugging\') app.logger.warning(\'A warning occurred (%d apples)\', 42) # app.logger.error(\'An error occurred\') # 获取当前的请求方式 app.logger.debug(request.method) # GET app.logger.debug(request.path) # /debug/ # 获取包含域名的完整URL地址 app.logger.debug(request.url) # http://127.0.0.1:5000/debug/ # 获取当前所有的路由信息 app.logger.debug(app.url_map) return "调试信息输出控制台" # 重定向到百度 @app.route("/baidu/") def function(): return redirect("http://www.baidu.com") # cookies设置 @app.route("/setCookies/") def setCookies(): res=make_response("设置namecookies") # 通过max_age控制cookie有效期, 单位:秒 res.set_cookie("namecookies",\'test cookies\',max_age=3600) return res # 获取cookies @app.route("/getCookies/") def getCookies(): return request.cookies.get(\'namecookies\') # 删除cookies @app.route("/delCookies/") def delCookies(): res=make_response("删除namecookies") res.delete_cookie("namecookies") return res import os app.secret_key = os.urandom(24) # 设置session @app.route("/setSession/") def setSession(): session[\'sessioninfo\'] = "session demo" return "session设置成功" # 获取session @app.route("/getSession/") def getSession(): return session[\'sessioninfo\'] # 删除session @app.route("/delSession/") def delSession(): session.pop(\'sessioninfo\', None) return "session删除成功" # 自定义404错误 @app.errorhandler(404) def page_not_found(e): return \'404\' # 自定义500错误 @app.errorhandler(500) def internal_server_error(e): return \'500\' # 启动程序 if __name__== \'__main__\': app.run( host = \'0.0.0.0\', port = 80, debug = True )