无用之flask学习

一、认识flask

  1、短小精悍、可扩展性强 的一个web框架

    注意:上下文管理机制

  2、依赖wsgi:werkzurg

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)

注意__init__和__call__的区别:

class Foo():
    def __init__(self):
        print('init')
    def __call__(self, *args, **kwargs):
        print('call')
a = Foo()
a()

#init
#call

一个简单的flask代码

from flask import Flask
app = Flask(__name__)
@app.route(
'/index') def index(): return 'hello world' if __name__ == '__main__': app.run('local

二、一个有登录功能的flask例子

  1、template可以类似django修改

  2、static有两种方式,

     A:  a、 static_folder="staticccc"  b、将static文件夹命名为 staticccc   c、img引用的时候用staticccc/xxxxx
    B: a、 static_url_path='/vvvvv' b、 img引用的时候用 /vvvvv/xxxxx
from flask import Flask,render_template,request,redirect,session

# app = Flask(__name__,template_folder="templates",static_folder="staticccc",static_url_path='/vvvvv')
app = Flask(__name__,template_folder="templates",static_folder="static")
app.secret_key = 'asdfasdf'

@app.route('/login',methods=["GET","POST"])
def login():
    if request.method == 'GET':
        return render_template('login.html')
  # request.args 获取的是get的信息 user
= request.form.get('user') #获取的是post的信息 pwd = request.form.get('pwd') if user == 'oldboy' and pwd == '666': session['user'] = user return redirect('/index') return render_template('login.html',error='用户名或密码错误') # return render_template('login.html',**{"error":'用户名或密码错误'}) @app.route('/index') def index(): user = session.get('user') if not user: return redirect('/login') return render_template('index.html') if __name__ == '__main__': app.run()

index.html

<body>
    <h1>欢迎使用</h1>
    <img src="/static/111.png" alt="">
</body>

login.html

<body>
    <h1>用户登录</h1>
    <form method="post">
        <input type="text" name="user">
        <input type="password" name="pwd">
        <input type="submit" value="提交">{{error}}
    </form>
</body>

猜你喜欢

转载自www.cnblogs.com/di2wu/p/10205468.html