如何python搭建簡單的服務,並實現post、get功能

如何python搭建簡單的服務,並實現post、get功能

問題背景

兩臺機器,其中一臺機器A需要計算,並且時刻把結果傳輸到另一臺機器B上。

最simple的方式,機器B搭建一個系列公共目錄,其中一個設置A有權限讀寫。A掛在B的公共目錄,把計算結果寫進去。B監控公共目錄,當有新的內容寫入時,讀取文件,當然,此處要考慮鎖的問題。這裏,反過來把公共目錄放在B上也是一樣的。這種場景下如果一臺機器是段側機器,一臺是服務器,那麼,在段側去存放這種目錄,需要記得設置文件存儲時間、大小,最好寫入信息的時候,就查看總的文件大小,免得磁盤寫滿。

正常情況下,在A或B上假設一個服務,另一臺機器去訪問就好了。如果是A做計算,相當於A先得到消息,B後得到消息。那麼,B上架一個服務,用A去訪問它是比較合適的。如果條件允許,在B上同時搞一個數據庫存儲結果和後續狀態,我覺得也是不錯的。

這裏,只講講怎麼在B上搭建服務,在A上創建請求。

工具

  1. python IDE,此處選擇了pycharm
  2. postman,下載地址:https://www.getpostman.com/downloads/

參考

  1. https://www.jianshu.com/p/279473392f38 【主要參考這個】
  2. https://blog.csdn.net/huaxiawudi/article/details/81612831 【簡單看看作爲理解,實際用還有很多需要補充】

搭建服務

服務就是,運行一個程序,等待發信任給我發數據,我讀到這些數據,做出處理,處理完成後,回覆一些數據。
在上面的場景中,就是A計算將結果發給B,B得到消息後做處理,處理之後給A回覆一條消息,A看到消息,就知道給B的信B已經收到了。
github上的大神分享了自己的code,參考1中有解讀。實際操作過程如下。
講下面代碼運行,將架起一個服務。

  • 搭建服務
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging


class S(BaseHTTPRequestHandler):
    def do_HEAD(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        paths = {
            '/foo': {'status': 200},
            '/bar': {'status': 302},
            '/baz': {'status': 404},
            '/qux': {'status': 500}
        }

        if self.path in paths:
            self.respond(paths[self.path])
        else:
            self.respond({'status': 500})
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))

    def do_POST(self):
        content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
        post_data = self.rfile.read(content_length) # <--- Gets the data itself

        logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
                str(self.path), str(self.headers), post_data.decode('utf-8'))

        res = "You Input: " + post_data.decode('utf-8')

        self.do_HEAD()
        # self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))
        self.wfile.write("{}".format(res).encode('utf-8'))
        # self.wfile.write("POST request for {ASS}".format(data).encode('utf-8'))

    def respond(self, opts):
        response = self.handle_http(opts['status'], self.path)
        self.wfile.write(response)

    def handle_http(self, status_code, path):
        self.send_response(status_code)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        content = '''
           <html><head><title>Title goes here.</title></head>
           <body><p>This is a test.</p>
           <p>You accessed path: {}</p>
           </body></html>
           '''.format(path)
        return bytes(content, 'UTF-8')


def run(server_class=HTTPServer, handler_class=S, port=8080):
    print("run()")
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...\n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print("httpd.server_close()")
    logging.info('Stopping httpd...\n')


if __name__ == '__main__':
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

當運行這段程序後,你可以利用postman創建一個post查看這個服務的效果。
記得要運行此程序,不要退出。服務就是一個一直在運行的程序。

查看服務的結果

首先看看你的ip地址,windows,cmd,ipconfig,得到我的本機地址是:192.168.1.108。
然後在postman中根據代碼中寫入的端口號8080,填寫被訪問的地址http://192.168.1.108:8080/TestServer,如果你不寫後面的後綴,也是可以的,http://192.168.1.108:8080,可以試試會看到什麼。這個url後綴,會在上面的服務中被解析,相當於處理服務的不同情況。
截圖如下,在這裏插入圖片描述

python實現post

在上面的場景中,如果B機器假設了服務,那麼A機器該如何利用python實現postman這樣一個動作呢?postman和K神已經幫我們解決了這個問題。操作如下
在這裏插入圖片描述
那麼,其中的code如下

import requests

url = "http://192.168.1.108:8080/TestServer"

payload = "abcdddddEEEE"
headers = {
    'Content-Type': "text/plain",
    'User-Agent': "PostmanRuntime/7.15.0",
    'Accept': "*/*",
    'Cache-Control': "no-cache",
    'Postman-Token': "d5639969-8fbd-4531-9ad5-9a1bbe99089a,0c1fee63-a3e2-4a81-89ea-8b8861a0aa61",
    'Host': "192.168.1.108:8080",
    'accept-encoding': "gzip, deflate",
    'content-length': "12",
    'Connection': "keep-alive",
    'cache-control': "no-cache"
    }

response = requests.request("POST", url, data=payload, headers=headers)

print(response.text)

運行這段代碼就實現了一個post功能。

或者,你用下面的這段代碼也是可以的。都來自postman。

import http.client

conn = http.client.HTTPConnection("192,168,1,108")

payload = "abcdddddEEEE"

headers = {
    'Content-Type': "text/plain",
    'User-Agent': "PostmanRuntime/7.15.0",
    'Accept': "*/*",
    'Cache-Control': "no-cache",
    'Postman-Token': "b695333f-e7e4-4926-8824-aea76482402b,48e619a9-f5a1-4898-9184-57cde4d72d89",
    'Host': "192.168.1.108:8080",
    'accept-encoding': "gzip, deflate",
    'content-length': "24",
    'Connection': "keep-alive",
    'cache-control': "no-cache"
    }

conn.request("POST", "TestServer", payload, headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

總結

按照以上的過程,你應該可以搞定一個python搭建服務,python實現post的基本功能。web服務和訪問有很多內容,此處只是應急的自己玩玩的小功能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章