2020/04/20 - [개발자/Python] - Pycharm (파이참) 소켓 서버 띄우기
2020/04/20 - [개발자/Python] - Postman (포스트맨)으로 GET, POST URL 보내기
URL : 'http://localhost:8090/api/v1/getrecord?city=seoul&zipcode=08206&mobile=01012341234&nickname=cat'
을 보냈을 때 Query의 Key, Value를 분리해서 각각 한 줄에 한 쌍씩 HTML 웹으로 출력하기.
수정한 부분
if recordID == "getrecord" :
split_url = (self.path.split('/')[-1]).split('?')[-1].split('&')
keyList = []
valueList = []
split_url_len = len(split_url)
for i in range(0,split_url_len,):
splitQuery = split_url[i].split('=')
keyList.append(splitQuery[0])
valueList.append(splitQuery[1])
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Send the html message
self.wfile.write(bytes("<html><head><title>Title goes here.</title></head>", "utf-8")) #"euc-kr"
self.wfile.write(bytes("<body><p>I hate enviromental error... T.T</p>", "utf-8"))
self.wfile.write(bytes("<p>Your accessed path: %s</p>" % self.path, "utf-8"))
for i in range(0, split_url_len,):
self.wfile.write(bytes(keyList[i] + " : " + valueList[i] + "<p>", "utf-8")) # 웹에 찍힌다.
for i in range(0, split_url_len,):
print(keyList[i], " : ", valueList[i]) # 콘솔에 찍힌다.
self.wfile.write(bytes("</body></html>", "utf-8"))
결과
전체 코드
#!/usr/bin/python
# -*- coding: utf-8 -*-
# from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
# 필요한 모듈을 불러옴.
from http.server import BaseHTTPRequestHandler,HTTPServer #소켓 서버 실행용
from socketserver import ThreadingMixIn # 아직 안 씀. 근데 왜 음영처리 되어있지?
import json # requests : response를 위해 json 형식을 사용함. Key:Value 쌍.
import re # Regular Expression (정규표현식) 모듈. 정규표현식이란? 문자열을 어떻게 처리할지에 대한 기준이 되는 표현 방식.
# 예를 들어 어떤 문장에서 숫자만 골라내고 싶은 경우, 어떤 특정 문자가 반복되는 경우 바꾼다던가, 그 문자를 기준으로 나눈다던가 하는 것이다.
from urllib.parse import parse_qs # URL 문자열을 구성 요소(주소 지정 체계, 네트워크 위치, 경로 등)으로 분리하고,
# 구성 요소를 다시 URL 문자열로 결합하고, '상대 URL'을 절대 'URL'로 변환하는 표준 인터페이스를 정의.
import cgi # Common Gateway Interface
PORT_NUMBER = 8090 # 전역변수. 어디선가 이걸 아래서 쓸거다.
# This class will handle any incoming request from
# a browser
class myHandler(BaseHTTPRequestHandler): # Type : class, Name : myHandler, Super class : BaseHTTPRequestHandler (저 위에 form http.server import...)
# Handler for the GET requests
def do_GET(self): # Override다. Super class인 BaseHTTPRequestHandler에 'do_GET' 함수가 있는데 Sub class인 myHandler에서 재정의해서 사용한다.
# 자바에서는 @Override를 붙여서 명시해줬지만 파이썬에서는 명시할 필요 없이 그냥 Super class에 있는 함수명을 그대로 가져다 다시 정의하면 된다.
print('Get request received')
if None != re.search('/api/v1/getrecord/*', self.path):
recordID = (self.path.split('/')[-1]).split('?')[0]
print("recordID = ", recordID)
if recordID == "getrecord" :
split_url = (self.path.split('/')[-1]).split('?')[-1].split('&')
keyList = []
valueList = []
split_url_len = len(split_url)
for i in range(0,split_url_len,):
splitQuery = split_url[i].split('=')
keyList.append(splitQuery[0])
valueList.append(splitQuery[1])
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Send the html message
self.wfile.write(bytes("<html><head><title>Title goes here.</title></head>", "utf-8")) #"euc-kr"
self.wfile.write(bytes("<body><p>I hate enviromental error... T.T</p>", "utf-8"))
self.wfile.write(bytes("<p>Your accessed path: %s</p>" % self.path, "utf-8"))
for i in range(0, split_url_len,):
self.wfile.write(bytes(keyList[i] + " : " + valueList[i] + "<p>", "utf-8")) # 웹에 찍힌다.
for i in range(0, split_url_len,):
print(keyList[i], " : ", valueList[i]) # 콘솔에 찍힌다.
self.wfile.write(bytes("</body></html>", "utf-8"))
else:
self.send_response(400, 'Bad Request: record does not exist')
self.send_header('Content-Type', 'application/json')
self.end_headers()
def do_POST(self):
if None != re.search('/api/v1/addrecord/*', self.path):
ctype, pdict = cgi.parse_header(self.headers['content-type']) # application/json;encoding=utf-8;lang=ko;loc=seoul;...
print(ctype) # application/json
print(pdict) # {encoding:utf-8, lang:ko, loc:seoul}
if ctype == 'application/json':
content_length = int(self.headers['Content-Length']) # 48 bytes
post_data = self.rfile.read(content_length) # .rfile.read( ) 읽어와라. (bytes로 읽어옴.)
receivedData = post_data.decode('utf-8') # .decode('utf-8')을 통해 우리가 아는 문자열로 바뀜.
print(type(receivedData))
tempDict = json.loads(receivedData) # load your str into a dict # 위에 문자열로 바꾼걸 다시 딕셔너리로 바꿈.
#print(type(tempDict)) #print(tempDict['this'])
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes(json.dumps(tempDict), "utf-8")) # 위에서 bytes -> str -> dic 으로 바꿔서 읽어들였던 것을 역순으로 해서 내보낸다. dic -> str -> bytes
elif ctype == 'application/x-www-form-urlencoded':
content_length = int(self.headers['content-length'])
# trouble shooting, below code ref : https://github.com/aws/chalice/issues/355
postvars = parse_qs((self.rfile.read(content_length)).decode('utf-8'),keep_blank_values=True)
#print(postvars) #print(type(postvars)) #print(postvars.keys())
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes(json.dumps(postvars) ,"utf-8"))
else:
self.send_response(403)
self.send_header('Content-Type', 'application/json')
self.end_headers()
else:
self.send_response(404)
self.send_header('Content-Type', 'application/json')
self.end_headers()
# ref : https://mafayyaz.wordpress.com/2013/02/08/writing-simple-http-server-in-python-with-rest-and-json/
return
try:
# Create a web server and define the handler to manage the
# incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler) # HTTPServer : 위에 불러온 모듈, '서비스 할 IP' : 공란은 모든 IP에 대해서 서비스를 하겠다.
# PORT_NUMBER : 위에 있는 전역변수 8090, myHandler : BaseHTTPRequestHandler를 상속 받은 오버라이드가 들어갔다.(도움말 열어보면 얘가 들어가야 한다 나옴.)
# HTTPServer에 (괄호)안의 것들을 생성자로 넘겨주는거다. 그렇 server라는 객체를 생성한다.
print ('Started httpserver on port ' , PORT_NUMBER)
# Wait forever for incoming http requests
server.serve_forever() # server 라는 객체를 실행시킨다.
except:
print ('^C received, shutting down the web server')
print("서버 종료1!!")
server.socket.close() # 8090 포트를 닫아준다. (이거 안 닫으면 계속 점유하게된다.) 자원해제하는 절차.
'개발자 > Python' 카테고리의 다른 글
Python (파이썬) 절대경로, 상대경로 (0) | 2020.04.22 |
---|---|
Python (파이썬) 웹 크롤링 기초 - Spark 퀴즈 정보 긁어오기 (0) | 2020.04.22 |
Postman (포스트맨)으로 GET, POST URL 보내기 (1) | 2020.04.20 |
Pycharm (파이참) 소켓 서버 띄우기 (0) | 2020.04.20 |
Python (파이썬) 웹 크롤링 User Agent (0) | 2020.04.14 |