python flask 总结以及一些各种传值问题

来源:互联网 发布:js 遍历div中的ul li 编辑:程序博客网 时间:2024/06/05 01:53

这几天刚用了用flask开发了一些网页,发现有很多的传值细节都很难搞定。楼主在这里列举一些例子,不过很多的东西楼主也没用过,以后慢慢补充。
1. 首先安装flask插件
2. 导入包
from flask import Flask, request, redirect, url_for
from flask import render_template

3.flask 运行的方法

app.run(debug=True)

4.网页地址栏与python代码的联系
python代码写

#方法名字随便起,不用和route中的名字相同,route中的名字只对浏览器访问的时候起作用。@app.route('/')def helloworld():    return 'helloword!'

浏览器地址则是

http://127.0.0.1:5000/

图例
示例

@app.route('/like')def name():    return 'MISS 大小姐'http://127.0.0.1:5000/like

图例

浏览器地址栏直接向方法传值

@app.route('/like'/<name1>,<name2>)def name(name1,name2):    return name1 + ' ' + name2http://127.0.0.1:5000/like/MISS,MISS

图例

5.方法向浏览器传值

@app.route('/list')def list():    count, res = db.query('select * from student')        return render_template("student/list.htm", data=res)

student/list.htm 中的代码片段

<div>        <table id="sample-table-1">        <thead>             <tr>                 <th>学号</th>                 <th>姓名</th>                 <th>年龄</th>                                 </tr>         </thead>             {% for row in data %}                 <tr>                     <td>{{ row[0] }}</td>                     <td>{{ row[1] }}</td>                     <td>{{ row[2] }}</td>                                                              </tr>             {% endfor %}     </table></div>

{% 这里写一些简单的代码%} 代码逻辑
{{这里写值的名字}} 传值
6.form 表单传值
页面

<form action="/save" method="post">    <input name="name" type="text"/>    <input type="submit" value="提交"/></form>

python

@app.route('/save',method=['POST'])def save():    name = request.form['name']    return name

7.python 与 js 的交互
经常会有字符 空格 ’ “” 等被转义成其他字符,这其实是特殊字符进行转义,防止js注入
在js中可以利用tojson解决。
比如数组 num = [“ni”],经过flask的 {{num}}传入js后,就变成了&#39;ni&#39;
解决方法
利用js的tojson
var myGeocode = {{ num|tojson }};
8. html 与 js 的交互

<button onclick="edit('{{row[0]}','{{row[1]}}')">#每个值一定要用单引号括起来,不然js出错js:function edit(id,name){    ...}

9.返回二进制文件

@app.route('/img')def img():    f = file("static/a/a.png","r")    bytes = f.read()    return bytes,200,{"Content-Type": 'image/jpeg'}

10.方法重定向

@app.route(/'redirect')def show_redirect(): #有两种方式    return redirect(url_for('img')) # 1    return img() # 2

11.session

@app.route('/session')def sessiontest():  # 演示用户级变量的session的用法    if session.get("user"): #获取必须使用get        return "already logined!"    else:        session["user"] = "1"        return "no login"

12.页面中使用 ajax 来进行局部刷新

<script>function edit(){    var list = [1,2,3,4];    $.post("/server",{"list":list}).done(function(data)){    alert(data);    }.fail(function(fail_data)){    alert(fail_data);}}</script>
@app.route('/server',method=["post"])def server():    list = request.form.getlist("list[]") #由于返回的是数组,要写成 'list[]'    print list    ...    return 'seccess!' #一定要有返回值

13.一些杂项

@app.route('/getpost', methods=['GET', 'POST'])def getpost():    print request.args.get("hage")  # 只返回get参数    print request.form.get("sex")  # 只返回post参数    print request.values.get("sex")  # 返回get与post参数,且get参数优先    print request.values.get("any")  # 不存在的变量返回None    print "method=" + request.method    print "path=" + request.path    print "host=" + request.host    print "url=" + request.url    print "remote_addr=" + request.remote_addr    print "headers=" + request.headers.__str__() #不是简单对象,需要这样转换为字符串    print "cookies=" + request.cookies.__str__()    return "done"
1 0
原创粉丝点击