Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pymysql
- from http.server import BaseHTTPRequestHandler, HTTPServer
- from urllib.parse import parse_qs, urlparse
- import json
- class testHTTPServer_RequestHandler(BaseHTTPRequestHandler):
- # GET
- def do_GET(self):
- # Send response status code
- self.send_response(200)
- # Send headers
- self.send_header('Content-type','application/json')
- self.end_headers()
- params = parse_qs(self.path)
- if len(params) > 0:
- query = 'SELECT * FROM products WHERE ' + ' AND '.join(
- [ str(i) + ' LIKE ' + str("'" + params[i][0] + "%'") for i in params])
- else:
- query = 'SELECT * FROM products'
- connection = pymysql.connect(host = '127.0.0.1',
- user = 'root',
- password = 'root',
- db = 'shop')
- with connection.cursor() as cursor:
- # Read a single record
- cursor.execute(query)
- json_array = []
- for row in cursor:
- json_array.append({
- 'id' : row[0],
- 'name' : row[1],
- 'category': row[2],
- 'description' : row[3]
- })
- # Send message back to client
- # Write content as utf-8 data
- message = json.dumps(json_array,ensure_ascii=False,indent=1)
- self.wfile.write(bytes(message, "utf8"))
- connection.close()
- return
- server_address = ('127.0.0.1', 8080)
- httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
- print('Server has been started')
- httpd.serve_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement