经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
大白话说Python+Flask入门(二)
来源:cnblogs  作者:久曲健  时间:2023/11/20 8:57:19  对本文有异议

写在前面

笔者技术真的很一般,也许只靠着笨鸟先飞的这种傻瓜坚持,才能在互联网行业侥幸的生存下来吧!

为什么这么说?

我曾不止一次在某群,看到说我写的东西一点技术含量都没有,而且很没营养,换作一年前的我,也许会怼回去,现在的话,我只是看到了,完事忘记了。

QQ截图20231118135309.png

早期写文章是为了当笔记用,不会随时查阅,当然也因为这个习惯,也结交了一些不嫌弃我的笨的朋友,真的很开心。

哈哈,回来别走神哈,来我们继续学习,老规矩,先上代码,拆知识点。

Flask的Api

1、Flask 静态文件

模版文件testJs.html,示例代码:

  1. <!DOCTYPE html>
  2. <head>
  3. <title>testJs</title>
  4. <script type = "text/javascript" src = "{{ url_for('static', filename = 'testjs.js') }}" ></script>
  5. </head>
  6. <body>
  7. JS测试 : <input type="button" value="点一下按钮" onclick="callJs()">
  8. </body>
  9. </html>

testjs.js文件代码:示例代码如下:

  1. function callJs() {
  2. alert('hello testJs!')
  3. }

逻辑代码如下:

  1. from flask import Flask,render_template
  2. app=Flask(__name__)
  3. @app.route("/")
  4. def index():
  5. return render_template("testJs.html")
  6. if __name__ == '__main__':
  7. app.run(host='0.0.0.0', port=8888, debug=False)

知识点:

  • 在项目下创建一个static文件,这个文件就是放testjs.js的位置,如JS、CSS这种文件
  • 模版文件引入静态文件固定写法:
  1. <script type = "text/javascript" src = "{{ url_for('static', filename = 'testjs.js') }}" ></script>

2、Request的使用

模版代码MarriageInformation.html,示例代码如下:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Marriage Information</title>
  6. </head>
  7. <body>
  8. <h3>基本信息</h3>
  9. <form action="http://localhost:8888/userinfo" method="post">
  10. <p>Name: <input type="text" name="name" ></p>
  11. <p>Height: <input type="text" name="height" ></p>
  12. <p>Age: <input type="text" name="age" ></p>
  13. <p>Sex: <input type="text" name="sex" ></p>
  14. <p>Education: <input type="text" name="education" ></p>
  15. <p>Hobby: <input type="text" name="hobby" ></p>
  16. <p><input type="submit" value="submit"></p>
  17. </form>
  18. </body>
  19. </html>

作用: 主要用于前端数据录入,是不是直接联想到常见的问卷啥的?

模版代码userinfo.html,示例代码如下:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>user Info</title>
  6. </head>
  7. <body>
  8. <h3>user Info</h3>
  9. <table border="0.5">
  10. {% for key ,value in userinfo.items() %}
  11. <tr>
  12. <th>{{key}}</th>
  13. <td>{{value}}</td>
  14. </tr>
  15. {% endfor %}
  16. </table>
  17. </body>
  18. </html>

作用: 主要用于展示你刚才你录入的信息。

逻辑代码,示例如下:

  1. from flask import Flask, render_template, request
  2. app = Flask(__name__)
  3. @app.route("/")
  4. def marryInfo():
  5. return render_template("MarriageInformation.html")
  6. @app.route('/userinfo',methods=['GET','POST'])
  7. def userinfo():
  8. userinfo = request.form
  9. return render_template("userinfo.html", userinfo=userinfo)
  10. if __name__ == '__main__':
  11. app.run(host='0.0.0.0', port=8888, debug=False)

效果:

知识点:

1、Request主要用于接收和处理客户端你提交的数据,Request对象的重要属性如下所列:

  • Form - 它是一个字典对象,包含表单参数及其值的键和值对。
  • args ****- 解析查询字符串的内容,它是问号(?)之后的URL的一部分。
  • Cookies - 保存Cookie名称和值的字典对象。
  • files - 与上传文件有关的数据。
  • method - 当前请求方法。

2、 {% for key ,value in userinfo.items() %}这个就是遍历属性, {% endfor %}就是结束遍历的意思。不会写怎么办?照着抄,抄完再改。

3、Cookie的使用

示例代码如下:

  1. from flask import Flask, make_response, request
  2. app = Flask(__name__)
  3. @app.route('/setCookie')
  4. def setCookie():
  5. res = make_response('Success!')
  6. res.set_cookie('login', 'true', max_age=3600)
  7. return res
  8. @app.route('/getCookie')
  9. def getCookie():
  10. cookies = request.cookies
  11. return cookies
  12. @app.route('/deleteCookie')
  13. def deleteCookie():
  14. res = make_response('deleteCookie, Success!')
  15. res.delete_cookie('login')
  16. return res
  17. if __name__ == '__main__':
  18. app.run(host='0.0.0.0', port=8888, debug=False)

设置cookie效果:

获取cookie效果:

删除cookie效果:

知识点:

  • 设置cookie:默认有效期是临时,浏览器关闭就失效,可以通过 max_age 设置有效期时间,单位是秒
  • 获取cookie:通过request.cookies的方式, 返回的是一个字典
  • 删除cookie:通过delete_cookie('cookie名字')的方式, 删除只是让cookie过期,而不是直接删除cookie
  • cookie只存在客户端

4、Session的使用

示例代码如下:

  1. from flask import Flask, request, session, url_for, redirect
  2. app = Flask(__name__)
  3. # 为每个客户端的会话分配会话ID,会话数据存储在cookie的顶部
  4. app.secret_key = 'nkladhnjldasjhnlksdnjklasdn'
  5. @app.route('/')
  6. def index():
  7. if 'usersession' in session:
  8. usersession = session['usersession']
  9. return usersession + ',已经登录了!' + '<br><a href="/logout" >请点击退出!</a>'
  10. return '您还没登录,<a href="/login" >请点击登录</a>'
  11. @app.route('/login', methods=['GET', 'POST'])
  12. def login():
  13. if request.method == 'POST':
  14. session['usersession'] = request.form['usersession']
  15. return redirect(url_for('index'))
  16. return '''
  17. <form action = "" method = "post">
  18. <p><input type="text" name="usersession"/></p>
  19. <p><input type="submit" value="Login"/></p>
  20. </form>
  21. '''
  22. @app.route('/logout')
  23. def logout():
  24. session.pop('usersession', None)
  25. return redirect(url_for('index'))
  26. if __name__ == '__main__':
  27. app.run(host='0.0.0.0', port=8888, debug=False)

效果:

知识点:

  • Session即会话,会话数据会存储在服务器上的临时目录中
  • Session是字典,成对存在
  • Session['username'] = 'admin':为'username'会话变量
  • session.pop('username', None):使用pop()方法,释放会话变量。
  • app.secret_key:为每个客户端的会话分配会话ID,会话数据存储在cookie的顶部

5、重定向的使用

示例代码如下:

  1. from flask import Flask, request, session, url_for, redirect, render_template, abort
  2. app = Flask(__name__)
  3. app.secret_key = 'nkladhnjldasjhnlksdnjklasdn'
  4. @app.route('/')
  5. def index():
  6. return render_template('login.html')
  7. @app.route('/login', methods=['GET', 'POST'])
  8. def login():
  9. if request.method == 'POST':
  10. username = request.form['username']
  11. if username == 'admin':
  12. return redirect(url_for('welcome'))
  13. else:
  14. abort(401)
  15. else:
  16. return redirect(url_for('index'))
  17. @app.route('/welcome')
  18. def welcome():
  19. return 'login Successs!'
  20. if __name__ == '__main__':
  21. app.run(host='0.0.0.0', port=8888, debug=False)

知识点:

1、redirect(location, statuscode, response): 用于跳转到指定位置

  • location:重定向的url路径
  • statuscode:状态码,默认为302。
  • response: 用于实例化响应。

2、abort(code): 错误码的函数,和HTTP协议的code码几乎一样,可自行了解。

6、上传文件的使用

可以理解为就是一个文件上传的功能。

模版文件代码:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>upload demo</title>
  6. </head>
  7. <body>
  8. <h2>upload demo</h2>
  9. <form action="http://localhost:8888/upload" method="POST" enctype="multipart/form-data">
  10. <input type="file" name="file">
  11. <input type="submit" value="upload">
  12. </form>
  13. </body>
  14. </html>

逻辑代码如下:

  1. import os.path
  2. from flask import Flask, request, url_for, redirect, render_template
  3. basedir = os.path.dirname(__file__)
  4. parentpath = os.path.dirname(basedir)
  5. app = Flask(__name__)
  6. @app.route('/')
  7. def index():
  8. return render_template('upload.html')
  9. @app.route('/upload', methods=['POST'])
  10. def upload():
  11. file = request.files['file']
  12. if file:
  13. filename = file.filename
  14. file.save(os.path.join(parentpath+'\upload', secure_filename(filename)))
  15. return 'upload Success!'
  16. else:
  17. return redirect(url_for('index'))
  18. if __name__ == '__main__':
  19. app.run(host='0.0.0.0', port=8888, debug=False)

效果:

知识点:

  • 在模版文件中加入:enctype 属性设置为“multipart/form-data”,表示在url中处理文件上传
  • 使用 secure_filename(filename) 函数,获取文件的安全版本
  • request.files[file] 这个函数用于获取提交文件,其中filename属性就是文件名,使用
  • upload 前面不能加“/”。会报错的

写在最后

看到这,你是不是感觉,我靠,这东西不就是jsp吗?

好过时的技术呀,哈哈,是不是心中的鄙视链和碎碎念就出来了!

没关系,感觉不要停,也不要欺骗自己,毕竟这感觉是真的呢。

但我想会,即便过时我也写,毕竟还是会有人看得,至少我看到公号上有四个小伙伴收藏了我的文章。

QQ截图20231118135251.png

换个角度,现实看,你会了怎么也比啥也写不出来强吧,所以尊重技术,好好的把“招数”拿出来就好了,至于什么招式这东西,完全趋于百炼成精,一种本能罢了。

我曾看过这样一个故事:

一个学者问老和尚说:师傅您在得道之前,每天都做什么呀?

老和尚说:砍柴、挑水、做饭。

学者有问:那得道后呢?

老和尚说:砍柴、挑水、做饭。

那何谓得道?

老和尚说:得道前,砍柴时惦记着挑水,挑水时惦记着做饭;得道后,砍柴就是砍柴,挑水就是挑水,做饭就是做饭。

所以学东西也一样,不如踏实的把一件事做好,啥都想干,倒是啥也干不好,不是吗!

好啦,今天好开心呢,因为比昨天又多会了几个知识点!

原文链接:https://www.cnblogs.com/longronglang/p/17841043.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号