WSGI(Web Server Gateway Interface,web服务器网关接口)主要规定了服务器端和应用程序之间的接口,即规定了请求的URL到后台处理函数之间的映射该如何实现。wsgiref是一个帮助开发者开发测试的Python内置库,程序员可以通过这个库了解WSGI的基本运行原理,但是不能把它用在生产环境上。

WSGI处理过程
  1. 浏览器到wsgi server :浏览器发送的请求会先到wsgi server
  2. environ: wsgi server 会将http请求中的参数等信息封装到environ(一个字典) 中
  3. wsgi server 到wsgi app :app就是我们编写的后台程序,每个url会映射到对于的入口处理函数,wsig server调用后台app时,会将environ和wsgi server中自己一个start_response函数注入到后台app中
  4. 逻辑处理:后台函数需要接受environ和start_response,进行逻辑处理后返回一个可迭代对象,可迭代对下中的元素为http正文
  5. wsgi app 到wsgi server:后台函数处理完后,会先调用start_response函数将http状态码,报文头等信息(响应头)返回给wsgi server,然后再将函数的返回值作为http正文(响应body)返回给wsgi server.
  6. 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服务器的更多相关文章

  1. Python搭建Web服务器,与Ajax交互,接收处理Get和Post请求的简易结构

    用python搭建web服务器,与ajax交互,接收处理Get和Post请求:简单实用,没有用框架,适用于简单需求,更多功能可进行扩展. python有自带模块BaseHTTPServer.CGIHT ...

  2. python搭建简易服务器实例参考

    有关python搭建简易服务器的方法. 需求分析: 省油宝用户数 已经破了6000,原有的静态报表 已经变得臃肿不堪, 每次打开都要缓上半天,甚至浏览器直接挂掉 采用python搭建一个最最简易的 w ...

  3. python搭建本地服务器

    python搭建本地服务器 python3以上版本 'python3 -m http.server 8000' 默认是8000端口,可以指定端口,打开浏览器输入http://127.0.0.1:800 ...

  4. [容器]python搭建简易服务器+docker导入多个镜像shell脚本

    从其他机器导出来的docker镜像,集中地放在某台上,其他的机器执行 curl xxx:8000/load_images.sh 来导入镜像,简单方便 使用python简易web服务器. (在镜像目录下 ...

  5. 使用Python搭建http服务器

    David Wheeler有一句名言:“计算机科学中的任何问题,都可以通过加上另一层间接的中间层解决.”为了提高Python网络服务的可移植性,Python社区在PEP 333中提出了Web服务器网关 ...

  6. python 搭建http服务器和ftp服务器

    默认安装版本为pytho2.7 http服务器搭建: 进入要开放访问的目录下,执行命令:python -m SimpleHTTPServer 9000 显示上述表示安装成功,且http服务的端口为:9 ...

  7. python 搭建ftp服务器

    代码示例: # coding: utf-8 import os from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.han ...

  8. python搭建ftp服务器

    1 # coding: utf-8 import os from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handler ...

  9. Python一秒搭建ftp服务器,帮助你在局域网共享文件【华为云技术分享】

    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/devcloud/article/detai ...

  10. Python一秒搭建ftp服务器,帮助你在局域网共享文件

    "老板 来碗面" "要啥面?" "内牛满面.." 最近项目上的事情弄得人心累,本来是帮着兄弟项目写套入口代码,搞着搞着就被拉着入坑了.搞开发 ...

随机推荐

  1. Java中的对象到底是什么

    对象是现实世界中的一切物体(实体,或能够定义的东西) Smalltalk是第一个成功的面向对象的语言 在编程世界中,对象通过类来实例化:同一个类型的对象可以接受相同的消息 状态+行为+标识=对象 每个 ...

  2. 微信小程序文件预览和下载-文件系统

    文件预览和下载 在下载之前,我们得先调用接口获取文件下载的url 然后通过wx.downloadFile将下载文件资源到本地 wx.downloadFile({ url: res.data.url, ...

  3. CentOS 7替换默认软件源

    安装CentOS 7后,默认源在国外,可以替换为国内的源以提升访问速度 参考https://mirrors.ustc.edu.cn/help/centos.html sudo vi /etc/yum. ...

  4. 【封装】二维BIT

    struct BIT{ #define maxn 1000 int n, m; int d1[maxn][maxn], d2[maxn][maxn], d3[maxn][maxn], d4[maxn] ...

  5. [ABC265D] Iroha and Haiku (New ABC Edition)

    Problem Statement There is a sequence $A=(A_0,\ldots,A_{N-1})$ of length $N$. Determine if there exi ...

  6. winform中也可以这样做数据展示✨

    1.前言 在做winform开发的过程中,经常需要做数据展示的功能,之前一直使用的是gridcontrol控件,今天想通过一个示例,跟大家介绍一下如何在winform blazor hybrid中使用 ...

  7. tensorflow GPU版本配置加速环境

    import tensorflow as tf tf.test.is_gpu_available() 背景 环境:Anaconda .tensorflow_gpu==1.4.0 (这里就用1.4.0版 ...

  8. 【UniApp】-uni-app-CompositionAPI传递数据

    前言 好,经过上个章节的介绍完毕之后,了解了一下 uni-app-传递数据 那么了解完了uni-app-传递数据之后,这篇文章来给大家介绍一下 uni-app-CompositionAPI传递数据 首 ...

  9. JWT 简介与 C# 示例

    〇.什么是 JWT ? JWT,即 JSON Web Token,是一种基于 JSON 的开放标准(RFC 7519),主要用于在网络应用环境间安全地传递声明.这种声明被进行了数字签名,可以验证和信任 ...

  10. Windows下使用C#和32feet.NET开发蓝牙传输功能的记录

    引用的第三方Nuget库 32feet.NET 3.5.0 MaterialDesignColors MaterialDesignThemes Newtonsoft.Json 使用到的技术: XAML ...