python 搭建HTTP服务器
WSGI(Web Server Gateway Interface,web服务器网关接口)主要规定了服务器端和应用程序之间的接口,即规定了请求的URL到后台处理函数之间的映射该如何实现。wsgiref是一个帮助开发者开发测试的Python内置库,程序员可以通过这个库了解WSGI的基本运行原理,但是不能把它用在生产环境上。
WSGI处理过程
- 浏览器到wsgi server :浏览器发送的请求会先到wsgi server
- environ: wsgi server 会将http请求中的参数等信息封装到environ(一个字典) 中
- wsgi server 到wsgi app :app就是我们编写的后台程序,每个url会映射到对于的入口处理函数,wsig server调用后台app时,会将environ和wsgi server中自己一个start_response函数注入到后台app中
- 逻辑处理:后台函数需要接受environ和start_response,进行逻辑处理后返回一个可迭代对象,可迭代对下中的元素为http正文
- wsgi app 到wsgi server:后台函数处理完后,会先调用start_response函数将http状态码,报文头等信息(响应头)返回给wsgi server,然后再将函数的返回值作为http正文(响应body)返回给wsgi server.
- wsgi server 到浏览器:wsgi server 将从app中等到的所有信息封装作为一个response返回给浏览器
import hashlib,requests,json,time,urllib.parse
from http import HTTPStatus
import dashscope
from wsgiref.simple_server import make_server
errStr ='''
{
"code" : -1,
"msg" : "not support"
}
'''
notStr = '''
{
"code" : -2,
"msg" : "not allowed"
}
'''
# For prerequisites running the following sample, visit https://help.aliyun.com/document_detail/611472.html
dashscope.api_key="api_key" # 自己的api_key
def al(cont):
messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '%s'%cont}]
response = dashscope.Generation.call(
dashscope.Generation.Models.qwen_turbo,
messages=messages,
result_format='message', # set the result to be "message" format.
)
if response.status_code == HTTPStatus.OK:
content = response['output']['choices'][0]['message']['content']
# print(content)
return content
else:
print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
response.request_id, response.status_code,
response.code, response.message
))
return errStr
# 通义千问
def Tongyi(cont):
url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
payload = json.dumps({
"model": "qwen-turbo",
"input": {
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": cont
}
]
},
"parameters": {}
})
headers = {
'Content-Type': 'application/json',
'Authorization': 'key' # 换成自己的key
}
response = requests.request("POST", url, headers=headers, data=payload)
msg = response.json()['output']['text']
return msg
# 青云客
def qingyunk(cont):
url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=%s" % (urllib.parse.quote(cont))
html = requests.get(url)
msg = html.json()['content']
return msg
def RunServer(environ,start_response):
# 添加回复内容的http头部信息,支持多个
headers = {'Content-Type': 'application/json', 'Custom-head1': 'Custom-info1'}
# environ 包含当前环境信息与请求信息,为字符串类型的键值对
current_url = environ['PATH_INFO']
current_content_length = environ['CONTENT_LENGTH']
current_request_method = environ['REQUEST_METHOD']
# 获取body json 内容转换为python对象
current_req_body = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))
current_req_json = json.loads(current_req_body)
# 获取输入值
cont = current_req_json['cont']
cont = urllib.parse.unquote(cont)
print(cont)
#打印请求信息
print("REQUEST METHOD:",current_request_method)
print("REQUEST URL:",current_url)
print("REQUEST BODY:",current_req_json)
#根据不同url回复不同内容
if current_url == "/qingyunk":
if current_request_method == "GET":
result = Tongyi(cont)
print(result)
# 拼装回复报文
successStr = '''
{
"code":200,
"msg":"success",
"data":{
"content":"%s"
}
}
''' % (result)
start_response("200 OK", list(headers.items()))
return [successStr.encode("utf-8"), ]
else:
start_response('403 not allowed',list(headers.items()))
return [notStr.encode("utf-8"),]
elif current_url == "/Tongyi":
result = qingyunk(cont)
print(result)
# 拼装回复报文
successStr = '''
{
"code":200,
"msg":"success",
"data":{
"content":"%s"
}
}
''' % (result)
start_response("200 OK", list(headers.items()))
return [successStr.encode("utf-8"), ]
elif current_url == '/al':
result = al(cont)
# 拼装回复报文
successStr = '''
{
"code":200,
"msg":"success",
"data":{
"content":"%s"
}
}
''' % (result)
start_response("200 OK", list(headers.items()))
return [successStr.encode("utf-8"), ]
else:
start_response("404 not found", list(headers.items()))
return [errStr.encode("utf-8"), ]
if __name__ == "__main__":
httpd = make_server('', 10000, RunServer)
host, port = httpd.socket.getsockname()
print('Serving running', host, 'port', port)
httpd.serve_forever()
WSGI web服务器
- 本质上是一个TCP服务器,监听在特定的端口上。
- 支持HTTP协议,能够解析HTTP请求报文,能够按HTTP协议将响应数据封装为报文并返回给浏览器。
- 实现了WSGI协议,该协议约定了和应用程序之间的接口,即url到app之间的映射。
WSGI应用程序
- 遵从WSGI协议。
- 本身是一个可调用对象。
- 调用start_response,返回响应头部。
- 返回包含正文的可迭代对象。
python 搭建HTTP服务器的更多相关文章
- Python搭建Web服务器,与Ajax交互,接收处理Get和Post请求的简易结构
用python搭建web服务器,与ajax交互,接收处理Get和Post请求:简单实用,没有用框架,适用于简单需求,更多功能可进行扩展. python有自带模块BaseHTTPServer.CGIHT ...
- python搭建简易服务器实例参考
有关python搭建简易服务器的方法. 需求分析: 省油宝用户数 已经破了6000,原有的静态报表 已经变得臃肿不堪, 每次打开都要缓上半天,甚至浏览器直接挂掉 采用python搭建一个最最简易的 w ...
- python搭建本地服务器
python搭建本地服务器 python3以上版本 'python3 -m http.server 8000' 默认是8000端口,可以指定端口,打开浏览器输入http://127.0.0.1:800 ...
- [容器]python搭建简易服务器+docker导入多个镜像shell脚本
从其他机器导出来的docker镜像,集中地放在某台上,其他的机器执行 curl xxx:8000/load_images.sh 来导入镜像,简单方便 使用python简易web服务器. (在镜像目录下 ...
- 使用Python搭建http服务器
David Wheeler有一句名言:“计算机科学中的任何问题,都可以通过加上另一层间接的中间层解决.”为了提高Python网络服务的可移植性,Python社区在PEP 333中提出了Web服务器网关 ...
- python 搭建http服务器和ftp服务器
默认安装版本为pytho2.7 http服务器搭建: 进入要开放访问的目录下,执行命令:python -m SimpleHTTPServer 9000 显示上述表示安装成功,且http服务的端口为:9 ...
- python 搭建ftp服务器
代码示例: # coding: utf-8 import os from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.han ...
- python搭建ftp服务器
1 # coding: utf-8 import os from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handler ...
- Python一秒搭建ftp服务器,帮助你在局域网共享文件【华为云技术分享】
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/devcloud/article/detai ...
- Python一秒搭建ftp服务器,帮助你在局域网共享文件
"老板 来碗面" "要啥面?" "内牛满面.." 最近项目上的事情弄得人心累,本来是帮着兄弟项目写套入口代码,搞着搞着就被拉着入坑了.搞开发 ...
随机推荐
- AtCoder Beginner Contest 240 F - Sum Sum Max
原题链接F - Sum Sum Max 首先令\(z_i = \sum\limits_{k = 1}^i y_k\),\(z_0 = 0\),\(z_i\)就是第\(i\)段相同的个数的前缀和. 对于 ...
- 🔥🔥Java开发者的Python快速进修指南:控制之if-else和循环技巧
简单介绍 在我们今天的学习中,让我们简要了解一下Python的控制流程.考虑到我们作为有着丰富Java开发经验的程序员,我们将跳过一些基础概念,如变量和数据类型.如果遇到不熟悉的内容,可以随时查阅文档 ...
- vivado仿真(无需testbench)
vivado仿真(无testbench) 实现步骤 新建一个工程并添加自己编写的Verilog文件 添加后vivado会自动识别文件中的module 创建block design文件,添加模块 添加前 ...
- 五分钟 k8s 实战-应用探针
今天进入 kubernetes 的运维部分(并不是运维 kubernetes,而是运维应用),其实日常我们大部分使用 kubernetes 的功能就是以往运维的工作,现在云原生将运维和研发关系变得更紧 ...
- RLHF · PBRL | B-Pref:生成多样非理性 preference,建立 PBRL benchmark
论文题目:B-Pref: Benchmarking Preference-Based Reinforcement Learning,2021 NeurIPS Track Datasets and Be ...
- Excel做数据分析?是真的很强!
当涉及到数据分析时,Excel无疑是一个功能强大且广泛应用的工具.它提供了丰富的功能和灵活性,使得用户可以进行各种复杂的数据处理和分析.在本文中, 我将详细介绍Excel在数据分析领域的强大功能,包括 ...
- idea常用快捷键使用
idea常用快捷键使用:1.shift+u 大小写2.alt+shift+u 驼峰命名(插件:CamelCase)3.ctrl+alt 点击跳转实现类4.ctrl 点击跳转接口类5.Alt+F7 查看 ...
- [HDU4117] GRE
Recently George is preparing for the Graduate Record Examinations (GRE for short). Obviously the mos ...
- 1、GO语言入门-环境准备
1.Windows开发环境准备 (1)Golang编译器下载 golang中文网:https://studygolang.com/dl 或者:https://go.dev/dl/ (2)下载解压,找到 ...
- 在蓝图中使用flask-restful
flask-restful中的Api如果传递整个app对象,那么就是整个flask应用都被包装成restful. 但是,你可以只针对某个蓝图(django中的子应用)来进行包装,这样就只有某个蓝图才会 ...