Python之Flask笔记

在这里先说一下最开始所经历的一些错误app=Flask(_name_),当初拼写的时候怎么都报错后来发现此处是两个'_'css

配置文件html

app.config.from_object(__name__)  在当前文件中查询配置项flask

app.config.from_envvar('FLASKR_SETTINGS', silent=True)    在文件中查询配置现,其中FLASKR_SETTINGS表明环境变量,silent=True表明Flask不关心该环境变量键值是否存在浏览器

 

@app.route('/')
def index():
    return 'This is index'
此处route修饰器把一个函数绑定到一个URL上,@app.route('hello'),这个意思就是http://127.0.0.1/hellocookie

@app.route('/user<username>')app

def show_user(username):函数

  return 'My name is %s'%username编码

此处route中<username>表明一个参数,在地址栏中输入http://127.0.0.1/user/Sky,网页则会返回My name is Skyurl

 

from flask import url_forspa

@app.route('/login')

def index():return '这是一个新的url'

print url_for('login')

此处url_for()来针对一个特定的函数构建一个 URL,在时运行则会print出所构造好的地址地址栏中输入http://127.0.0.1/login便可访问
为何你要构建 URLs 而不是在模版中硬编码?这里有三个好的理由:
   1. 反向构建一般比硬编码更具有描述性。更重要的是,它容许你一次性修改 URL, 而不是处处找 URL 修改。
   2.构建 URL 可以显式地处理特殊字符和Unicode转义,所以你没必要去处理这些。
   3.若是你的应用不在 URL 根目录下(好比,在 /myapplication 而不在 /),url_for()将会适当地替你处理好。

放置静态文件时给静态文件生成URL

url_for('static',filename='style.css')

这个文件是应该存储在文件系统上的static/style.css

渲染文件

from flask import render_template

@app.route('/hello/')

@app.route('/hello<name>')

def hello(name=None):

  return render_template('hello.html',name=name)

此处将会从templates处查找模版文件hello.html

 请求对象

from flask import request

request.method==['GET','POST']

文件上传

在HTML表单中设置属性enctype="multipart/form-data",不然浏览器不会传送文件

from flask import request

@app.route('/upload',methods=['GET','POST'])

def upload_file():

  if request.method=='POST'

  f=request.files['file']

  f.save('/uploads'+secure_filename(f.filename))      由于客户端的名称可能会被伪造,因此永远不要相信,传递给secure_filename来打到效果

COOKIE操做

读取cookie:

  username=request.cookies.get('username')

存储cookie:

  from flask import make_response,render_template

  loadc=make_response(render_template())

  loadc.set_cookie('usernmae','the username')

重定向

错误重定向

若是出现出错的话能够定义一个装饰器

@app.errorhandler(404)    表明没有该文件

def page_not_found(error):

  return render_tamplater('**.html'),404      此处404是在render_tamplate调用,告诉Flask该页的错误代码是404

 

 

未完待续...

相关文章
相关标签/搜索