人工智能学习(一):Flask框架的重点与细节--快速入门(长期更新)

一、虚拟环境

二、Flask视图基础和URL

  1. Content-type:可以指定服务器与客户端之间传输数据类型和数据的编码类型

    Mime-type:不能指定传输的数据编码类型(Content-type>Mine-type)

  2. pycharm2017.1开启debug模式的方法:

    1. app.run(debug=True)
    2. app.debug=True
    3. app.config.update(DEBUG=True)
    4. 创建文件config.py ==> 写入DEBUG=True ==>import config ==> app.config.from_object(config)
    5. 创建文件config.py ==> 写入DEBUG=True ==>import config ==> app.config.from_pyfile(config.py)
    6. pycharm2018以上在configuration中修改FLASK_DEBUG打勾,Additional options: --host=0.0.0.0 --port=8000
  3. 第一种传递参数方式(路径):

    @app.route('/article/<id>/')
    def article(id):
        print(id)
        return "你传入的id为:%s"%id
    
  4. 参数类型:string int float path uuid

    @app.route('/<any(user,blog):module>/<int:id>/')
    def list1(module, id):  
        if module=='blog':
            return "博客详情:%s"%id
        else:
            return "用户详情:%s"%id
    
  5. 第二中参数传递方式

    1. get请求:request.args.get(‘uname’)
    2. post请求:request.form.get(‘uname’)
    from flask import request
    @app.route('/list7/',methods=['GET','POST'])
    def list2():
        if request.method == 'GET':
            uname = request.args.get('uname')
            pwd = request.args.get('pwd')
            return render_template('login.html')
        elif request.method == 'POST':
            uname = request.form.get('uname')
            pwd = request.form['pwd']
            return "接收到的参数为:%s %s" %(uname,pwd)
    
  6. 使用url_for() 函授构建url, 接收两个以上的参数,第一个参数为”[函数名]“,接受对应url规则的命名函数,(//)如果出现其他参数,会添加到url的后面作为查询参数(?key=value)

  7. 自定义URL转化器

    1. regex= 用来按对应规则捕获参数
    2. to_python(self,value) 用来操作URL中参数返回value(URL到函数中参数时生效)
    3. to_url(self,value)在调用url_for()传入参数时生效(url_for()到URL时生效)
    from werkzeug.routing import BaseConverter
    class TelephoneConveter(BaseConverter):
        regex = r"1[345789]\d{9}"
    
    app.url_map.converters['tel'] = TelephoneConveter
    
  8. return redirect()重定向

三、Flask之Jinja2模板

  1. 修改tempate的默认路径

    app = Flask(__name__,template_folder='d:/demo')
    
  2. render_remplate()传递多个参数, content是一个字典

    return render_template('/news/news_list.html',**content) #使用传参技巧
    return render_template('/news/news_list.html',c = content) #不使用传参技巧
    
  3. 过滤器基本语法 { {variable|过滤器名字}}

    <p>位置的绝对值为:{
        {position|abs}}</p>
    
  4. 常见过滤器:

    • abs(value):返回一个数值的绝对值。 例如:-1|abs。

    • default(value,default_value,boolean=false):如果当前变量没有值,则会使用参数中的值来代替。name|default(‘xiaotuo’)——如果name不存在,则会使用xiaotuo来替代。boolean=False默认是在只有这个变量为undefined的时候才会使用default中的值,如果想使用python的形式判断是否为false,则可以传递boolean=true。也可以使用or来替换。

    • escape(value)或e:转义字符,会将<、>等符号转义成HTML中的符号。例如:content|escape或content|e。

    • first(value):返回一个序列的第一个元素。names|first。

    • format(value,*arags,**kwargs):格式化字符串。例如以下代码:

      { { “%s” - “%s”|format(‘Hello?’,“Foo!”) }}将输出:Helloo? - Foo!

    • last(value):返回一个序列的最后一个元素。示例:names|last。

    • length(value):返回一个序列或者字典的长度。示例:names|length。

    • join(value,d=’+’):将一个序列用d这个参数的值拼接成字符串。

    • safe(value):如果开启了全局转义,那么safe过滤器会将变量关掉转义。示例:content_html|safe。

    • int(value):将值转换为int类型。

    • float(value):将值转换为float类型。

    • lower(value):将字符串转换为小写。

    • upper(value):将字符串转换为小写。

    • replace(value,old,new): 替换将old替换为new的字符串。

    • truncate(value,length=255,killwords=False):截取length长度的字符串。

    • striptags(value):删除字符串中所有的HTML标签,如果出现多个空格,将替换成一个空格。

    • trim:截取字符串前面和后面的空白字符。

    • string(value):将变量转换成字符串。

    • wordcount(s):计算一个长字符串中单词的个数。

    • reverse() 反向遍历

  5. ‘autoescape’ jinja标签可以对里面的代码块开启或关闭自动转义

    {% autoescape off %}
    	...代码块
    {% endautoescape %}
    
  6. 自定义过滤器:

    @app.template_filter('cut')
    def cut(value):
        value = value.replace("abc","***")
        return value
    
  7. 将模板设置为自动加载模式(可以加载templates中的html文件):

    app.config['TEMPLATES_AUTO_RELOAD']=True
    
  8. 条件判断语句if:

    {% if age>=18 %}
    	<p>已经成年</p>
    {% elif age>10 %}
    	<p>未成年</p>
    {% else %}
    	<p>你太小了</p>
    {% endif %}
    
  9. 循环语句for:(没有continue 和 break 语句)

    {% for user in users %}
      
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值