検索
ホームページバックエンド開発Python チュートリアルPython を使用してデバイスをシンプルなサーバーに変える方法。

How to Turn Your Device Into a Simple Server Using Python.

著者: Trix Cyrus

デバイスからホストされる 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("<h1 id="About-Us">About Us</h1><p>This is a custom Python server.</p>")
        elif parsed_path.path == '/greet':
            name = query.get('name', ['stranger'])[0]
            self.respond_with_text(f"<h1 id="Hello-name">Hello, {name}!</h1>")
        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("<h1 id="POST-request-received">POST request received</h1>")

    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

以下のコードを貼り付けます



    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Python Simple Server</title>


    <h1 id="Welcome-to-My-Python-Server">Welcome to My Python Server!</h1>
    <p>This is a simple web server running on your local device.</p>


ステップ 2: ルートをテストする

変更したスクリプトを実行した後、次の場所に移動します。

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 を使用してデバイスをシンプルなサーバーに変える方法。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Pythonの融合リスト:適切な方法を選択しますPythonの融合リスト:適切な方法を選択しますMay 14, 2025 am 12:11 AM

Tomergelistsinpython、あなたはオペレーター、extendmethod、listcomfulting、olitertools.chain、それぞれの特異的advantages:1)operatorissimplebutlessforlargelist;

Python 3の2つのリストを連結する方法は?Python 3の2つのリストを連結する方法は?May 14, 2025 am 12:09 AM

Python 3では、2つのリストをさまざまな方法で接続できます。1)小さなリストに適したオペレーターを使用しますが、大きなリストには非効率的です。 2)メモリ効率が高い大規模なリストに適した拡張方法を使用しますが、元のリストは変更されます。 3)元のリストを変更せずに、複数のリストをマージするのに適した *オペレーターを使用します。 4)Itertools.chainを使用します。これは、メモリ効率が高い大きなデータセットに適しています。

Python Concatenateリスト文字列Python Concatenateリスト文字列May 14, 2025 am 12:08 AM

Join()メソッドを使用することは、Pythonのリストから文字列を接続する最も効率的な方法です。 1)join()メソッドを使用して、効率的で読みやすくなります。 2)サイクルは、大きなリストに演算子を非効率的に使用します。 3)リスト理解とJoin()の組み合わせは、変換が必要なシナリオに適しています。 4)redoce()メソッドは、他のタイプの削減に適していますが、文字列の連結には非効率的です。完全な文は終了します。

Pythonの実行、それは何ですか?Pythonの実行、それは何ですか?May 14, 2025 am 12:06 AM

pythonexexecutionistheprocessoftransforningpythoncodeintoexecutabletructions.1)interpreterreadSthecode、変換intobytecode、thepythonvirtualmachine(pvm)executes.2)theglobalinterpreeterlock(gil)管理委員会、

Python:重要な機能は何ですかPython:重要な機能は何ですかMay 14, 2025 am 12:02 AM

Pythonの主な機能には次のものがあります。1。構文は簡潔で理解しやすく、初心者に適しています。 2。動的タイプシステム、開発速度の向上。 3。複数のタスクをサポートするリッチ標準ライブラリ。 4.強力なコミュニティとエコシステム、広範なサポートを提供する。 5。スクリプトと迅速なプロトタイピングに適した解釈。 6.さまざまなプログラミングスタイルに適したマルチパラダイムサポート。

Python:コンパイラまたはインタープリター?Python:コンパイラまたはインタープリター?May 13, 2025 am 12:10 AM

Pythonは解釈された言語ですが、コンパイルプロセスも含まれています。 1)Pythonコードは最初にBytecodeにコンパイルされます。 2)ByteCodeは、Python Virtual Machineによって解釈および実行されます。 3)このハイブリッドメカニズムにより、Pythonは柔軟で効率的になりますが、完全にコンパイルされた言語ほど高速ではありません。

ループvs whileループ用のpython:いつ使用するか?ループvs whileループ用のpython:いつ使用するか?May 13, 2025 am 12:07 AM

useaforloopwhenteratingoverasequenceor foraspificnumberoftimes; useawhileloopwhentinuninguntinuntilaConditionismet.forloopsareidealforknownownownownownownoptinuptinuptinuptinuptinutionsituations whileoopsuitsituations withinterminedationations。

Pythonループ:最も一般的なエラーPythonループ:最も一般的なエラーMay 13, 2025 am 12:07 AM

pythonloopscanleadtoErrorslikeinfiniteloops、ModifiningListsDuringiteration、Off-Oneerrors、Zero-dexingissues、およびNestededLoopinefficiencies.toavoidhese:1)use'i

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール