flask学习
Posted yinwenjie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask学习相关的知识,希望对你有一定的参考价值。
特点:
短小精悍,可扩展性强
依赖wsgi:werkzurg
werkzurg示例:
from werkzeug.wrappers import Request, Response from werkzeug.serving import run_simple def run(environ,start_response): return [b"asdfasdf"] if __name__ == ‘__main__‘: run_simple(‘localhost‘, 4000, run)
from werkzeug.wrappers import Request, Response @Request.application def hello(request): return Response(‘Hello World!‘) if __name__ == ‘__main__‘: from werkzeug.serving import run_simple run_simple(‘localhost‘, 4000, hello)
#访问index则可以得到Hello World from flask import Flask app = Flask(__name__) @app.route("/index") def run(): return "Hello World" if __name__ == "__main__": app.run()
实现一个登陆验证的功能:
from flask import Flask,render_template,request,redirect,session app = Flask(__name__) #一般用__name__,但是用其他只要是字符串都行 app.secret_key = "asdfsg" #给session加密的盐 @app.route("/login",methods=["GET","POST"]) def login(): if request.method == "GET": return render_template("login.html") user = request.form.get("user") #request.args相当于request.GET,request.form相当于request.POST pwd = request.form.get("pwd") if user=="xxx" and pwd=="xxx": session["user"] = user #flask的session其实是cookie,但是加了密 return redirect("/index") else: return render_template("login.html",error="用户名或密码错误") #或者可以写成**{error:"用户名或密码错误"} @app.route("/index") #不写methods默认只接受GET请求 def index(): user = session.get("user") if not user: return redirect("/login") return render_template("index.html") if __name__ == "__main__": app.run()
以上是关于flask学习的主要内容,如果未能解决你的问题,请参考以下文章