0

0

如何使用 Python 将您的设备变成简单的服务器

DDD

DDD

发布时间:2024-09-23 19:46:42

|

698人浏览过

|

来源于dev.to

转载

如何使用 python 将您的设备变成简单的服务器

作者:特里克斯·赛勒斯

让我们创建一个从您的设备托管的 python 服务器。

开始..

创建一个名为server的目录

mkdir server

创建一个名为 server.py 的文件

nano server.py

粘贴以下代码。

import http.server
import socketserver
import logging
import os
import threading
from urllib.parse import urlparse, parse_qs

port = 8080
directory = "www"  

logging.basicconfig(level=logging.info, format='%(asctime)s - %(message)s', datefmt='%y-%m-%d %h:%m:%s')

class myhandler(http.server.simplehttprequesthandler):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=directory, **kwargs)

    def log_message(self, format, *args):
        logging.info("%s - %s" % (self.client_address[0], format % args))

    def do_get(self):
        parsed_path = urlparse(self.path)
        query = parse_qs(parsed_path.query)

        # custom logic for different routes
        if parsed_path.path == '/':
            self.serve_file("index.html")
        elif parsed_path.path == '/about':
            self.respond_with_text("

about us

this is a custom python server.

立即学习Python免费学习笔记(深入)”;

") elif parsed_path.path == '/greet': name = query.get('name', ['stranger'])[0] self.respond_with_text(f"

hello, {name}!

") else: self.send_error(404, "file not found") def do_post(self): content_length = int(self.headers['content-length']) post_data = self.rfile.read(content_length) logging.info("received post data: %s", post_data.decode('utf-8')) self.respond_with_text("

post request received

") def serve_file(self, filename): if os.path.exists(os.path.join(directory, filename)): self.send_response(200) self.send_header("content-type", "text/html") self.end_headers() with open(os.path.join(directory, filename), 'rb') as file: self.wfile.write(file.read()) else: self.send_error(404, "file not found") def respond_with_text(self, content): self.send_response(200) self.send_header("content-type", "text/html") self.end_headers() self.wfile.write(content.encode('utf-8')) class threadedhttpserver(socketserver.threadingmixin, http.server.httpserver): daemon_threads = true # handle requests in separate threads def run_server(): try: with threadedhttpserver(("", port), myhandler) as httpd: logging.info(f"serving http on port {port}") logging.info(f"serving files from directory: {directory}") httpd.serve_forever() except exception as e: logging.error(f"error starting server: {e}") except keyboardinterrupt: logging.info("server stopped by user") if __name__ == "__main__": server_thread = threading.thread(target=run_server) server_thread.start() server_thread.join()

创建一个名为www的目录

mkdir www

现在导航到 www 目录

cd www

创建一个名为index.html的文件

nano index.html

将以下代码粘贴到其中




    
    
    python simple server


    

welcome to my python server!

this is a simple web server running on your local device.

第 2 步:测试路由

智能网站优化SiteSEO1.52
智能网站优化SiteSEO1.52

系统易学易懂,用户只需会上网、不需学习编程及任何语言,只要使用该系统平台,只要会打字,即可在线直接完成建站所有工作。本程序适合不懂php环境配置的新手用来在本机调试智能SiteSEO网站优化软件,安装过程极其简单。您的网站地址:http://localhost您的网站后台:登录地址: http://localhost/admin.php密 码: admin服务器套件所包含的软件:nginx-0.7

下载

运行修改后的脚本后,转到:

http://localhost:8080/ 查看主页。
http://localhost:8080/about 查看关于页面。
http://localhost:8080/greet?name=trix
对于任何其他路径,服务器将返回 404 错误。

下面是目录结构

server/
├── server.py
└── www/
    └── index.html

在远程设备上运行服务器

如果您想从同一网络上的另一台设备访问您的 python 服务器怎么办?您可以通过查找运行服务器的计算机的本地 ip 地址并使用它而不是 localhost 来轻松完成此操作。

第 1 步:查找您的 ip 地址

使用类似
的命令

ipconfig
ifconfig

查找您的 ipv4 地址(例如 192.168.x.x)。

步骤 2. 修改您的服务器脚本

在您的服务器脚本中,替换启动服务器的行:

with threadedhttpserver(("", port), myhandler) as httpd:

更改为:

with ThreadedHTTPServer(("0.0.0.0", PORT), MyHandler) as httpd:

第 3 步:从另一台设备访问服务器

现在,使用您之前找到的 ip 地址,您可以通过浏览器中访问 http://:8080 从同一网络上的任何设备访问服务器。

一切就绪

~trixsec

相关专题

更多
python开发工具
python开发工具

php中文网为大家提供各种python开发工具,好的开发工具,可帮助开发者攻克编程学习中的基础障碍,理解每一行源代码在程序执行时在计算机中的过程。php中文网还为大家带来python相关课程以及相关文章等内容,供大家免费下载使用。

716

2023.06.15

python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

626

2023.07.20

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

739

2023.07.25

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

617

2023.07.31

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

1236

2023.08.03

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

547

2023.08.04

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

575

2023.08.04

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

699

2023.08.11

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

62

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 0.6万人学习

Django 教程
Django 教程

共28课时 | 2.6万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.0万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号