Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Python3 enable its own http service?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces Python3 how to open its own http service related knowledge, detailed and easy to understand, simple and fast operation, has a certain reference value, I believe that everyone will have a harvest after reading this Python3 how to open its own http service article, let's take a look at it.

Start Web Services 1. Basic Ways

Python comes with a simple server program that makes it easier to open services.

In python3, change the original SimpleHTTPServer command to http.server. Use it as follows:

1. cd www directory

2. python -m http.server

If it is enabled successfully, it will output "Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0:8000/)...", indicating that the service is enabled on port 8000 of the local computer.

If you need to run in the background, you can add an "&" symbol after the command. Ctrl+C will not turn off the service, as follows:

python -m http.server &

If you want to maintain service, add nohup before the command to ignore all hang-up signals, as follows:

nohup python -m http.server 80012. Specify port

If you do not use the default port, you can attach port parameters when opening, such as:

python -m http.server 8001

http service is opened on port 8001.

using Web Services

You can use http://0.0.0:8000/to view web pages under the www directory. If there is no index.html, the files under the directory will be displayed.

You can also use the ifconfig command to view the native IP and use the.

Python creates http services

background

Invalid memory access often appears when calling dll with java, instead java-Python-dll

Python provides functionality to java via http services.

environment

Python3.7

Processing the request via http.server.BaseHTTPRequestHandler and returning a response

print log

filename is the name of the input log. By default, it is under the same directory. If there is no such file, it will be newly created.

filemode a is the mode of appending write, w is overwriting write

import logginglogging.basicConfig( level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', filename="hhh.txt", filemode ='a ')logging.info("xxxx") calls dll

pchar - ctypes.c_char_p

integer bytes(0), byref(ctypes.c_void_p(0)) are OK, no further study, if there is an error please correct.

import ctypesfrom ctypes import *dll = ctypes.windll.LoadLibrary('C:\xxx\xxx.dll')print("dll version number is: "+ 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 option 1

response = response_start_line + response_headers + " " + response_body

After splicing the response message, it can be returned correctly to the browser.

# coding:utf-8import socketfrom multiprocessing import Processdef handle_client(client_socket): #Get client request data request_data = client_socket.recv(1024) print("request:", request_data) #Construct Response Data response_start_line = "HTTP/1.1 200 OK" response_headers = "Server: My server" response_body = "helloWorld! " response = response_start_line + response_headers + "" + response_body print("response:", response) #Return response data to client client_socket.send(bytes(response, "utf-8")) #Close client connection 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] user connected" % client_address) handle_client_process = Process(target=handle_client, args=(client_socket,)) handle_client_process.start() client_socket.close() Full code

Another HTTP method.

#-.- coding:utf-8 -.- from http.server import HTTPServerimport ctypesfrom ctypes import *# HTTPRequestHandler classimport http.serverimport socketserverimport logging# pyinstaller -Fclass 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 your specific business operations 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() package exepip install pyinstaller

pyinstaller -F xxx.py, generated under the current directory

pit

1、No module named 'http.server'; 'http' is not a package

At that time, I created a py called http, which was normal after deletion.

2、UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position 130: invalid continuat

Save as utf-8

About "Python 3 how to open its own http service" The content of this article is introduced here, thank you for reading! I believe everyone has a certain understanding of the knowledge of "how to open Python 3 with http service." If you still want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report