一 Flask学习(基础)

1、快速入门

from flask import Flask

#实例化对象

app = Flask(__name__)

# 将 '/' 和 函数index的对应关系添加到路由中。

{

"/":index        

}

@app.route("/")

def index()

        return"hello"

1.1、登陆模块

from flask import Flask, render_template, request, redirect
#render_template 发送template模块下的html文件
#redirect 发送反射其他网址链接
app = Flask(__name__)
app.debug = True


@app.route("/login", methods=["GET", "POST"], endpoint="l1")
#参数methods支持的请求方法,endpoint给路由设置别名
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        # request.query_string
        request form表单的格式,通过request.form 提起表单的数据
        user = request.form.get("user")
        pwd = request.form.get("pwd")
        if user == "alex" and pwd == "123":
            return redirect('http://www.luffycity.com')
        #
        else:
            return render_template("login.html", error="用户名密码错误")
        #error 设置的参数,html可以通过{{error}}调用

1.2、表单信息模块 Index
USERS = {
    1:{'name':'张桂坤','age':18,'gender':'男','text':"当眼泪掉下来的时候,是真的累了, 其实人生就是这样: 你有你的烦,我有我的难,人人都有无声的泪,人人都有难言的苦。 忘不了的昨天,忙不完的今天,想不到的明天,走不完的人生,过不完的坎坷,越不过的无奈,听不完的谎言,看不透的人心放不下的牵挂,经历不完的酸甜苦辣,这就是人生,这就是生活。"},
    2:{'name':'主城','age':28,'gender':'男','text':"高中的时候有一个同学家里穷,每顿饭都是膜膜加点水,有时候吃点咸菜,我们六科老师每天下课都叫他去办公室回答问题背诵课文,然后说太晚啦一起吃个饭,后来他考上了人大,拿到通知书的时候给每个老师磕了一个头"},
    3:{'name':'服城','age':18,'gender':'女','text':"高中的时候有一个同学家里穷,每顿饭都是膜膜加点水,有时候吃点咸菜,我们六科老师每天下课都叫他去办公室回答问题背诵课文,然后说太晚啦一起吃个饭,后来他考上了人大,拿到通知书的时候给每个老师磕了一个头"},
}
@app.route('/detail/',methods=['GET'])
#参数变量 捕捉到请求,传递给函数 detail(nid):
def detail(nid):
    user = session.get('user_info')
    if not user:
        return redirect('/login')

    info = USERS.get(nid)
#通过键值对key (nid) 拿到对应信息,传给html
    return render_template('detail.html',info=info)
@app.route('/index', methods=['GET'])
def index():
    user = session.get('user_info')
    if not user:
        # return redirect('/login')
        url = url_for('l1')
#url_for  拿到设置别名的地址 直接返回
        return redirect(url)
    return render_template("index.html", user_dict=USERS)
if __name__ == '__main__':
    app.run()

2. 配置文件

settings.py 配置文件
class Config(object):
    DEBUG = False
    TESTING = False
    DATABASE_URI = 'sqlite://:memory:'


class ProductionConfig(Config):
    DATABASE_URI = 'mysql://user@localhost/foo'


class DevelopmentConfig(Config):
    DEBUG = True


class TestingConfig(Config):
    TESTING = True
from flask import Flask

app = Flask(__name__)
app.debug = True
app.secret_key = "asdfasdf"

app.config.from_object("settings.DevelopmentConfig")
通过类文件settings,导入DevelopmentConfig类 直接调用配置文件
@app.route('/')
def index():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

3. 路由系统

"""
1. decorator = app.route('/',methods=['GET','POST'],endpoint='n1')
    def route(self, rule, **options):
        # app对象
        # rule= /
        # options = {methods=['GET','POST'],endpoint='n1'}
        def decorator(f):
            endpoint = options.pop('endpoint', None)
            self.add_url_rule(rule, endpoint, f, **options)
            return f
        return decorator
2. @decorator
    decorator(index)
"""
@app.route('/',methods=['GET','POST'],endpoint='n1')
def index():
    return 'Hello World!'


def login():
    return '登录'
装饰器
相当于如下
app.add_url_rule('/login', 'n2', login, methods=['GET',"POST"])


4. 参数

4.1 defaults={'nid':888} 设置参数传递给函数
@app.route('/',methods=['GET','POST'],endpoint='n1',defaults={'nid':888})
def index(nid):
    print(nid)
    return 'Hello World!'


def login():
    return '登录'
app.add_url_rule('/login', 'n2', login, methods=['GET',"POST"])

4.2 redirect_to="/index2" 重定向  

@app.route('/index',methods=['GET','POST'],endpoint='n1',redirect_to="/index2")
def index():
    return '公司老首页'


@app.route('/index2',methods=['GET','POST'],endpoint='n2')
def index2():
    return '公司新首页'

4.3 子域名
app.config['SERVER_NAME'] = 'oldboyedu.com:5000'


@app.route("/", subdomain="admin")
def static_index():
    """Flask supports static subdomains
    This is available at static.your-domain.tld"""
    return "xxxxxx.your-domain.tld"


@app.route("/dynamic", subdomain="")
def username_index(username):
    """Dynamic subdomains are also supported
    Try going to user1.your-domain.tld/dynamic"""
    return username + ".your-domain.tld"

PS: hosts文件
            C:\Windows\System32\drivers\etc\hosts

            /etc/hosts
            
        小工具:脚本 py文件【为公司测试人员开发的修改host文件的小程序】
                python run.py 127.0.0.1 www.oldboyedu.com
                
                会议室预定
                
                调查问卷

5.模板语言

from flask import Flask,render_template,Markup,jsonify,make_response
app = Flask(__name__)


def func1(arg):
    return Markup("" %(arg,))
如果时候输入框 后台需要处理下

@app.route('/')
def index():
    # return jsonify({'k1':'v1'})
    # return render_template('s10index.html',ff = func1)
将函数传到html里, {{ff('六五')}}
    # response =  make_response("asdfasdf")
    # response.set_cookie
    # return response
    pass

6.session & cookie

rom flask import Flask,session
app = Flask(__name__)
app.secret_key = 'sdfsdf'

@app.route('/')
def index():
    # flask内置的使用 加密cookie(签名cookie)来保存数据。
    session['k1'] = 'v1'
    session['k2'] = 'v2'
    return 'xxx'

你可能感兴趣的:(flask,学习,python)