Python3如何开启⾃带http服务开启Web服务
1.基本⽅式
Python中⾃带了简单的服务器程序,能较容易地打开服务。
在python3中将原来的SimpleHTTPServer命令改为了http.server,使⽤⽅法如下:
1. cd www⽬录
2. python -m http.server
如果需要后台运⾏,可在命令后加"&"符号,Ctrl+C不会关闭服务,如下:
python -m http.server &
如果要保持服务,则在命令前加nohup以忽略所有挂断信号,如下:
nohup python -m http.server 8001
2.指定端⼝
如果不使⽤默认端⼝,可在开启时附带端⼝参数,如:
python -m http.server 8001
则会在8001端⼝打开http服务。
使⽤Web服务
也可以使⽤ifconfig命令查看本机IP并使⽤。
补充:python创建http服务
背景
⽤java调⽤dll的时候经常出现 invalid memory access,改⽤java-Python-dll,
Python通过http服务给java提供功能。
环境
如何打开端口Python3.7
通过 http.server.BaseHTTPRequestHandler 来处理请求,并返回response
打印⽇志
filename为输⼊⽇志名称,默认是同⽬录下,没有该⽂件会新创建
filemode a 是追加写的模式,w是覆盖写
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
filename="",
filemode='a'
)
logging.info("xxxx")
调⽤dll
pchar - ctypes.c_char_p
integer ⽤了 bytes(0),byref(ctypes.c_void_p(0)) 都OK,没有更深⼊去研究,如有错误请指正。import ctypes
from ctypes import *
dll = ctypes.windll.LoadLibrary('C:\ xx\ xx.dll')
print("dll版本号为: "+ str(dll.GetVersion()) )
name = ctypes.c_char_p(b"gc")
roomno = ctypes.c_char_p(de("utf-8")))
begintime = ctypes.c_char_p(de("utf-8")))
endtime = ctypes.c_char_p(de("utf-8")))
cardno = ctypes.c_void_p(0)
http⽅案⼀
要注意必须有 response = response_start_line + response_headers + “\r\n” + response_body
拼接应答报⽂后,才能给浏览器正确返回
# coding:utf-8
import socket
from multiprocessing import Process
def handle_client(client_socket):
# 获取客户端请求数据
request_data = v(1024)
print("request:", request_data)
# 构造响应数据
response_start_line = "HTTP/1.1 200 OK\r\n"
response_headers = "Server: My server\r\n"
response_body = "helloWorld!"
response = response_start_line + response_headers + "\r\n" + response_body
print("response:", response)
# 向客户端返回响应数据
client_socket.send(bytes(response, "utf-8"))
# 关闭客户端连接
client_socket.close()
if __name__ == "__main__":
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", 8888))
server_socket.listen(120)
print("success")
while True:
client_socket, client_address = server_socket.accept()
print("[%s, %s]⽤户连接上了" % client_address)
handle_client_process = Process(target=handle_client, args=(client_socket,))
handle_client_process.start()
client_socket.close()
完整代码
另外⼀种http⽅式
#-.- coding:utf-8 -.-
from http.server import HTTPServer
import ctypes
from ctypes import *
# HTTPRequestHandler class
import http.server
import socketserver
import logging
# pyinstaller -F
class testHTTPServer_RequestHandler(http.server.BaseHTTPRequestHandler):
# GET
def do_GET(self):
<('start make ')
str2 = str(self.path)
print("revice: " + str2)
if "xxx" in str2:
# todo 你的具体业务操作
if "xxx" in str2:
print("hahaha")
<('hahaha')
# response_body = "0"
self.send_response(200)
# Send headers
self.send_header('Content-type','text/html')
# Send message back to client
message = "Hello world!"
# Write content as utf-8 data
self.wfile.write(bytes(message, "utf8"))
return
else:
print("1else")
self.send_response(200)
# Send headers
self.send_header('Content-type', 'text/html')
# Send message back to client
message = "Hello world222333!"
# Write content as utf-8 data
self.wfile.write(bytes(message, "utf8"))
return
def run():
print('')
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
filename="http_",
filemode='a+'
)
# Server settings
server_address = ('127.0.0.1', 8888)
httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
print('')
httpd.serve_forever()
run()
打包exe
pip install pyinstaller
pyinstaller -F xxx.py 即可,当前⽬录下⽣成
坑
1、No module named ‘http.server'; ‘http' is not a package
当时⾃⼰建了⼀个py叫http,删掉后正常
2、UnicodeDecodeError: ‘utf-8' codec can't decode byte 0xce in position 130: invalid continuat 另存为utf-8即可
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论