Python3 如何开启自带http服务


Posted in Python onMay 18, 2021

开启Web服务

1.基本方式

Python中自带了简单的服务器程序,能较容易地打开服务。

在python3中将原来的SimpleHTTPServer命令改为了http.server,使用方法如下:

1. cd www目录

2. python -m http.server

开启成功,则会输出“Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) …”,表示在本机8000端口开启了服务。

如果需要后台运行,可在命令后加"&"符号,Ctrl+C不会关闭服务,如下:

python -m http.server &

如果要保持服务,则在命令前加nohup以忽略所有挂断信号,如下:

nohup python -m http.server 8001

2.指定端口

如果不使用默认端口,可在开启时附带端口参数,如:

python -m http.server 8001

则会在8001端口打开http服务。

使用Web服务

可以使用http://0.0.0.0:8000/查看www目录下的网页文件,若无index.html则会显示目录下的文件。

也可以使用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="hhh.txt",
    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:\\xxx\\xxx.dll')
print("dll版本号为 : "+ str(dll.GetVersion()) )
 name = ctypes.c_char_p(b"gc")
            roomno = ctypes.c_char_p(bytes(room.encode("utf-8")))
            begintime = ctypes.c_char_p(bytes(begin.encode("utf-8")))
            endtime = ctypes.c_char_p(bytes(end.encode("utf-8")))
            cardno = ctypes.c_void_p(0)
            dll.invoke...

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 = client_socket.recv(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):
        logging.error('start make ')
        str2 =  str(self.path)
        print("revice: " + str2)
        if "xxx" in str2:
            # todo 你的具体业务操作
               
            if "xxx" in str2:
                print("hahaha")
                logging.error('hahaha')
                # response_body = "0"
                self.send_response(200)
                # Send headers
                self.send_header('Content-type','text/html')
                self.end_headers()
                # 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')
            self.end_headers()
            # Send message back to client
            message = "Hello world222333!"
            # Write content as utf-8 data
            self.wfile.write(bytes(message, "utf8"))
            return
            
def run():
  print('starting server...')
  logging.basicConfig(
      level=logging.INFO,
      format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
      filename="http_make_card.txt",
      filemode='a+'
  )
  # Server settings
  server_address = ('127.0.0.1', 8888)
  httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
  print('running server...')
  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即可

Python3 如何开启自带http服务

以上为个人经验,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python私有属性和方法实例分析
Jan 15 Python
Python的Django框架中的select_related函数对QuerySet 查询的优化
Apr 01 Python
在python中利用opencv简单做图片比对的方法
Jan 24 Python
Python中类的创建和实例化操作示例
Feb 27 Python
python中数组和矩阵乘法及使用总结(推荐)
May 18 Python
Python3.6+Django2.0以上 xadmin站点的配置和使用教程图解
Jun 04 Python
python 利用已有Ner模型进行数据清洗合并代码
Dec 24 Python
Python urlencode和unquote函数使用实例解析
Mar 31 Python
python实现控制台输出彩色字体
Apr 05 Python
Python OpenCV实现测量图片物体宽度
May 27 Python
Pandas中DataFrame基本函数整理(小结)
Jul 20 Python
Python实例方法、类方法、静态方法区别详解
Sep 05 Python
安装pytorch时报sslerror错误的解决方案
Pytorch 如何实现LSTM时间序列预测
pytorch实现ResNet结构的实例代码
pytorch常用数据类型所占字节数对照表一览
May 17 #Python
python使用tkinter实现透明窗体上绘制随机出现的小球(实例代码)
Python编写可视化界面的全过程(Python+PyCharm+PyQt)
Pytorch 实现变量类型转换
You might like
繁体中文转换为简体中文的PHP函数
2006/10/09 PHP
PHP 远程关机实现代码
2009/11/10 PHP
php上传图片到指定位置路径保存到数据库的具体实现
2013/12/30 PHP
php网页版聊天软件实现代码
2016/08/12 PHP
php中加密解密DES类的简单使用方法示例
2020/03/26 PHP
基于jquery的时间段实现代码
2012/08/02 Javascript
禁用JavaScript控制台调试的方法
2014/03/07 Javascript
JS组件中bootstrap multiselect两大组件较量
2016/01/26 Javascript
JS集成fckeditor及判断内容是否为空的方法
2016/05/27 Javascript
AngularJS Bootstrap详细介绍及实例代码
2016/07/28 Javascript
JavaScript实现页面定时刷新(定时器,meta)
2016/10/12 Javascript
Vue中的Vux配置指南
2017/12/08 Javascript
详解如何在webpack中做预渲染降低首屏空白时间
2018/08/22 Javascript
vue 优化CDN加速的方法示例
2018/09/19 Javascript
浅谈vue限制文本框输入数字的正确姿势
2019/09/02 Javascript
如何解决vue在ios微信"复制链接"功能问题
2020/03/26 Javascript
Nodejs在局域网配置https访问的实现方法
2020/10/17 NodeJs
对Python中的@classmethod用法详解
2018/04/21 Python
使用python将图片按标签分入不同文件夹的方法
2018/12/08 Python
浅谈Django中view对数据库的调用方法
2019/07/18 Python
Pandas之read_csv()读取文件跳过报错行的解决
2020/04/21 Python
pycharm开发一个简单界面和通用mvc模板(操作方法图解)
2020/05/27 Python
html5定位获取当前位置并在百度地图上显示
2014/08/22 HTML / CSS
师范大学音乐表演专业求职信
2013/10/23 职场文书
大学教师年终总结的自我评价
2013/10/29 职场文书
秋季运动会稿件
2014/01/30 职场文书
群众路线教育实践活动对照检查材料
2014/09/22 职场文书
学校元旦晚会开场白
2014/12/14 职场文书
环境建议书
2015/02/04 职场文书
小学新教师个人总结
2015/02/05 职场文书
婚礼父母致辞
2015/07/28 职场文书
化工生产实习心得体会
2016/01/22 职场文书
学校2016年全国助残日活动总结
2016/04/01 职场文书
导游词之无锡古运河
2019/11/14 职场文书
浏览器常用基本操作之python3+selenium4自动化测试(基础篇3)
2021/05/21 Python
Vue ECharts实现机舱座位选择展示功能
2022/05/15 Vue.js