Last active
April 27, 2021 06:49
-
-
Save jtuttas/3ffd03c13979b25b48c8f442428327a5 to your computer and use it in GitHub Desktop.
PythonServer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
data = { | |
"temp": 22.5 | |
} | |
headers = {'Content-type': 'application/json'} | |
r = requests.post('http://localhost:8080?temp=19', json=data, headers=headers) | |
print(str(r)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python 3 server example | |
from http.server import BaseHTTPRequestHandler, HTTPServer | |
import time | |
from urllib.parse import urlparse, parse_qs | |
import json as simplejson | |
hostName = "localhost" | |
serverPort = 8080 | |
class MyServer(BaseHTTPRequestHandler): | |
def do_GET(self): | |
print("Habe einen Request:") | |
url = self.path | |
parsed = urlparse(url) | |
print(parse_qs(parsed.query)['temp']) | |
self.send_response(200) | |
self.send_header("Content-type", "application/json") | |
self.end_headers() | |
self.wfile.write(bytes("{\"success\":true}", "utf-8")) | |
def do_POST(self): | |
print("Habe einen POST Request:") | |
url = self.path | |
parsed = urlparse(url) | |
print(parse_qs(parsed.query)['temp']) | |
content_len = int(self.headers.get('content-length', 0)) | |
post_body = self.rfile.read(content_len) | |
test_data = simplejson.loads(post_body) | |
print ("post_body:"+str(test_data)) | |
print ("Temp is "+str(test_data["temp"])) | |
self.send_response(200) | |
self.send_header("Content-type", "application/json") | |
self.end_headers() | |
self.wfile.write(bytes("{\"Postsuccess\":true}", "utf-8")) | |
if __name__ == "__main__": | |
webServer = HTTPServer((hostName, serverPort), MyServer) | |
print("Server started http://%s:%s" % (hostName, serverPort)) | |
try: | |
webServer.serve_forever() | |
except KeyboardInterrupt: | |
pass | |
webServer.server_close() | |
print("Server stopped.") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### GET Request zum Server | |
GET http://localhost:8080?temp=22.4 HTTP/1.1 | |
#### POST Request zum Server | |
POST http://localhost:8080?temp=19.5 HTTP/1.1 | |
content-type: application/json | |
{ | |
"name":"tuttas", | |
"temp": 19.5 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment