首页 文章 精选 留言 我的

精选列表

搜索[ Web安全],共10000篇文章
优秀的个人博客,低调大师

使用Python-Flask框架开发Web网站系列课程(一)构建项目

版权声明:如需转载,请注明转载地址。 https://blog.csdn.net/oJohnny123/article/details/81907475 前言 使用IDE:PyCharm 操作系统: Mac Python版本:3.6 我的邮箱:51263921@qq.com 交流群: 372430835 请注意,既然要学习开发,那么要注意以下几个问题。 1、开发语言版本不一样,尤其是Python,会导致同一段代码压根跑不起来的情况。所以请保证版本一致。 2、操作系统不一样,自然也会有区分,但是Mac环境和Linux环境基本还是比较相近,贴合生产,所以使用Mac作为演示环境。但与Window的差别也不会很大。 3、简易使用一样的IDE工具,但是不强求。 4、本课代码的github地址在页面最底。 构建项目 一、创建虚拟环境venv 1、从前我很皮,不喜欢创建这东西,都是直接用系统环境的Python,后来项目一多,呵呵哒,这个项目用的Django1.9,那个项目又用Django2.0。得,乱套了。所以,请养成良好的习惯,使用venv大人。 2、通过PyCharm添加虚拟环境venv ,Windows在File->Settings,Mac在PyCharm->Preferences, 打开页面后,按下图配置。Add local Python Interpreter。最后 Apply -> OK。 二、安装flask 2.1 看下图,在Terminal控件里面执行 pip install flask==1.0.2 。 2.2 然后我们将这个阶段的依赖包记录下来,使用的命令为: pip freeze>requirement.txt 2.3 我们开始构建目录结构 我们需要一个目录放前端的代码(frontend),一个放后端代码(backend),一个放公共方法代码(utils),一个放配置文件(config)。 我们在根目录myproject里面右键New->Python Package,用这个创建包。按上面括号里面的名字建。 2.4 构建后端代码 2.4.1 添加config.py,在/myproject/config下。 这东西就是我们网站以后所有配置存放的地方啦,其中Config放的是各个环境都一致的配置,ProdConfig放的是生产环境的配置,SitConfig存放SIT环境配置,其他类比。 最后的一行,代表config = SitConfig() 当前获取的是SIT环境的配置。 全路径为:/myproject/config/config.py 内容如下: #!/usr/bin/python # -*- coding: UTF-8 -*- """ Created by liaoyangyang1 on 2017/11/8. """ import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) class Config(object): """Base config class.""" # 版本 VERSION = 'beta 0.1' # 项目名称 PROJECTNAME = 'myproject' # 端口 PORT = 10101 SECRET_KEY = '1234567890!@#$%^&*()' class ProdConfig(Config): """Production config class.""" # 是否开启调试 DEBUG = False # 主机ip地址 HOST = '0.0.0.0' class SitConfig(Config): """Development config class.""" # Open the DEBUG # 是否开启调试 DEBUG = True # 主机ip地址 HOST = '127.0.0.1' class DevConfig(Config): pass # Default using Config settings, you can write if/else for different env config = SitConfig() 2.4.2 修改/myproject/backend/__init__.py 这个是未来整个后端的入口文件,具体内容如下: 全路径:/myproject/backend/__init__.py 具体代码如下: #!/usr/bin/python # -*- coding: UTF-8 -*- """ Created by liaoyangyang1 on 2018/8/21 下午2:41. """ from flask import Flask from config.config import config def create_app(): #初始化项目实例 app = Flask(__name__) app.secret_key = app.config['SECRET_KEY'] #导入配置项 app.config.from_object(config) # 钩子 在请求执行之前 @app.before_request def before_request(): print('hi') return app 2.4.3 在根目录添加后端项目管理文件 manage.py 要先补一个模块 pip install Flask-Script==2.0.6 添加一个空的python脚本,manage.py 全路径:/myproject/manage.py 内容如下: #!/usr/bin/python # -*- coding: UTF-8 -*- """ Created by liaoyangyang1 on 2018/8/21 下午3:40. """ from flask_script import Manager, Server from backend import create_app app = create_app() app.debug = app.config["DEBUG"] # 获取根目录config.py的配置项 host = app.config["HOST"] port = app.config["PORT"] # Init manager object via app object manager = Manager(app) # Create a new commands: server # This command will be run the Flask development_env server manager.add_command("runserver", Server(host=host,port=port,threaded=True)) @manager.shell def make_shell_context(): """Create a python CLI. return: Default import object type: `Dict` """ # 确保有导入 Flask app object,否则启动的 CLI 上下文中仍然没有 app 对象 return dict(app=app) if __name__ == '__main__': manager.run() 2.4.4 添加视图文件,views.py 我们访问一个链接,要显示或者返回什么东西,就是在这里处理后返回给浏览器或者接口的。 全路径:/myproject/backend/views.py 内容如下: #!/usr/bin/python # -*- coding: UTF-8 -*- """ Created by liaoyangyang1 on 2018/8/21 下午3:51. """ from flask import Blueprint,jsonify #账户的蓝图 访问http://host:port/account 这个链接的子链接,都会跳到这里 account = Blueprint('/account', __name__) # 访问http://host:port/account/test 这个链接,就会跳到这里 @account.route('/test') #上面的链接,绑定的就是这个方法,我们给浏览器或者接口请求 一个json格式的返回 def test(): return jsonify({'code':0,'content':'hi flask'}) 2.4.5 添加路由文件,urls.py 全路径:/myproject/backend/urls.py 内容为: #!/usr/bin/python # -*- coding: UTF-8 -*- """ Created by liaoyangyang1 on 2018/8/21 下午3:50. """ from backend.views import account # 蓝图注册 def register(app): app.register_blueprint(account, url_prefix='/account', strict_slashes=False) 2.4.6 最后一步,添加内容到入口文件__init__.py 我们添加了两行代码 from backend.urls import register register(app) 用来干啥的呢,是要把我们路由蓝图的对应关系注册到我们的 flask实例里面。和我们之前把配置文件注册到app.config里面是一个道理。 路径:/myproject/backend/__init__.py 内容如下: #!/usr/bin/python # -*- coding: UTF-8 -*- """ Created by liaoyangyang1 on 2018/8/21 下午2:41. """ from flask import Flask from config.config import config from backend.urls import register def create_app(): #初始化项目实例 app = Flask(__name__) app.secret_key = app.config['SECRET_KEY'] #导入配置项 app.config.from_object(config) # 注册路由 register(app) # 钩子 在请求执行之前 @app.before_request def before_request(): print('hi') return app 三、启动项目 3.1 点击根目录的manage.py,右键执行 执行方式如图1,然后我们会发现还是缺了参数,请看图2、图3,通过edit configurations,在弹出框中的 Parameters 里面输入runserver。Apply后OK。 现在再次点击根目录的manage.py,右键执行。 * Serving Flask app "backend" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Running on http://127.0.0.1:10101/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 110-176-230 现在,我们在浏览器输入 http://127.0.0.1:10101/account/test 图1: 图2 图3 四、GITHUB地址 https://github.com/lyy8510a/myproject/releases/tag/v1

优秀的个人博客,低调大师

SpringCloud+SpringBoot+mybatis分布式微服务云架构开发Web应用

在完成配置之后,举一个简单的例子,在快速入门工程的基础上,举一个简单的示例来通过Thymeleaf渲染一个页面。 @Controller public class HelloController { @RequestMapping("/") public String index(ModelMap map) { // 加入一个属性,用来在模板中读取 map.addAttribute("host", "http://blog.didispace.com"); // return模板文件的名称,对应src/main/resources/templates/index.html return "index"; } } <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title></title> </head> <body> <h1 th:text="${host}">Hello World</h1> </body> </html> 如上页面,直接打开html页面展现Hello World,但是启动程序后,访问http://localhost:8080/,则是展示Controller中host的值:http://blog.didispace.com,做到了不破坏HTML自身内容的数据逻辑分离。 更多Thymeleaf的页面语法,还请访问Thymeleaf的官方文档查询使用。 Thymeleaf的默认参数配置 如有需要修改默认配置的时候,只需复制下面要修改的属性到application.properties中,并修改成需要的值,如修改模板文件的扩展名,修改默认的模板路径等。 # Enable template caching. spring.thymeleaf.cache=true # Check that the templates location exists. spring.thymeleaf.check-template-location=true # Content-Type value. spring.thymeleaf.content-type=text/html # Enable MVC Thymeleaf view resolution. spring.thymeleaf.enabled=true # Template encoding. spring.thymeleaf.encoding=UTF-8 # Comma-separated list of view names that should be excluded from resolution. spring.thymeleaf.excluded-view-names= # Template mode to be applied to templates. See also StandardTemplateModeHandlers. spring.thymeleaf.mode=HTML5 # Prefix that gets prepended to view names when building a URL. spring.thymeleaf.prefix=classpath:/templates/ # Suffix that gets appended to view names when building a URL. spring.thymeleaf.suffix=.html spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved. 支持JSP的配置Spring Boot并不建议使用,但如果一定要使用,可以参考此工程作为脚手架:JSP支持 完整项目的源码来源 技术支持1791743380

优秀的个人博客,低调大师

基于hi-nginx的web开发(python篇)——表单处理和文件上传

hi-nginx会自动处理表单,所以,在hi.py框架里,要做的就是直接使用这些数据。 表单数据一般用GET和POST方法提交。hi-nginx会把这些数据解析出来,放在form成员变量里。对python来说,要做的就是使用has_form和get_form方法取出想要的数据。 例如路由如下: @app.route('^/form/?$',['GET','POST']) def form(req,res,param): name='None' if req.has_form('name'): name=req.get_form('name') res.content('{}={}'.format('name',name)) res.status(200) 上面的路由表示可以使用get和post两种方法向/form提交名为name的数据。可以用curl测试下: curl -i http://localhost:8080/form?name=123 或者 curl -i -d 'name=123' http://localhost:8080/form hi.py处理表单的方式就是这么直接简单。 以上路由还可以直接处理文件上传,只需把name理解为上传文件的临时地址就可以了: echo 'test upload file' > name.file curl -i -F'name=@name.file' http://localhost:8080/form 上图表示当我们把文件name.file上传给/form时,该文件会被暂时保存在hi-nginx安装目录下的temp目录中,文件名为temp/94ffcfe29b03c0c7368a2fdd842d54ca.file。因此,我们要做的仅仅是把该文件移动到想要的地址去就行了。 因为文件有大小,服务器也会对文件大小做出限制,所以最好是使用nginx的client_max_body_size,比如 client_max_body_size 100k; 命令限制文件上传的大小限制。

优秀的个人博客,低调大师

基于hi-nginx的web开发(python篇)——动态路由和请求方法

hi.py 的提供的路由装饰器接受两个参数,第一个参数指定动态路由的正则模式,第二个参数指定同意的http请求方法列表。 比如: 1 @app.route(r"^/client/?$",['GET','POST']) 2 def client(req,res,param): 3 res.content('{}<br>{}<br>{}<br>{}<br>{}'.format(req.client(),req.method(),req.uri(),req.user_agent(),req.param())) 4 res.status(200) 这个路由指定uri为/client或者/client/,同时请求方法为GET或者POST的http请求由函数client(req,res,param)来处理。uri模式由正则表达式构成,请求方法参数由一个list表示,可接受的方法名包括:GET,POST,PUT,HEAD,PATCH等,凡nginx能理解的http方法名均可。 处理函数有三个参数,分别是req,res和param。它们分别是hi_req,hi_res和由正则表达式引出的group dict。前两者是有hi-nginx提供的api,它们提供一系列方法来操控http协议: hi_req uri method client param user_agent has_header get_header has_form get_form has_session get_session has_cookie get_cookie hi_res status content header session 处理函数的第三个参数param可用来解析由正则模式提供的数据,比如: 1 @app.route(r"^/hello/(?P<who>\w+)?$",['GET']) 2 def hello(req,res,param): 3 res.content('{}={}'.format('who',param['who'])) 4 res.status(200) 正则模式^/hello/(?P<who>\w+)?$ 是python re模块可以理解的模式,当uri为/hello/cnblogs时,其中的参数param就会是一个包含以who为键,以cnblogs为其值的dict字典。因此,它可以用来为操作函数提供表单以外的数据,还能美化uri。比如/hello?who=cnblogs就不如/hello/cnblogs美观简洁。 另外,同一个操作函数也可以对应多个路由规则,比如: 1 @app.route(r'^/test/?$',['POST']) 2 @app.route(r"^/$",['GET']) 3 def hello_world(req,res,param): 4 res.header('Content-Type','text/plain;charset=utf-8') 5 res.content('hello,world') 6 res.status(200) 在上面的代码中,操作函数hello_world在uri为/或者/test或者/test/时均能被调用,前提是一个要求请求方法是GET,另一个则要求是POST方法。这种一个函数对应多个路由的功能消除了写下面这种代码的麻烦: 1 if req.method()=='GET': 2 ... 3 if req.method()=='POST': 4 ...

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册
修改密码
忘记密码