Advertisement
Guest User

Untitled

a guest
Jul 24th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. import pymysql
  2.  
  3. from http.server import BaseHTTPRequestHandler, HTTPServer
  4. from urllib.parse import parse_qs, urlparse
  5.  
  6. import json
  7.  
  8. class testHTTPServer_RequestHandler(BaseHTTPRequestHandler):
  9.  
  10. # GET
  11. def do_GET(self):
  12. # Send response status code
  13. self.send_response(200)
  14.  
  15. # Send headers
  16. self.send_header('Content-type','application/json')
  17. self.end_headers()
  18.  
  19. params = parse_qs(self.path)
  20.  
  21. if len(params) > 0:
  22. query = 'SELECT * FROM products WHERE ' + ' AND '.join(
  23. [ str(i) + ' LIKE ' + str("'" + params[i][0] + "%'") for i in params])
  24. else:
  25. query = 'SELECT * FROM products'
  26.  
  27. connection = pymysql.connect(host = '127.0.0.1',
  28. user = 'root',
  29. password = 'root',
  30. db = 'shop')
  31.  
  32. with connection.cursor() as cursor:
  33. # Read a single record
  34. cursor.execute(query)
  35. json_array = []
  36. for row in cursor:
  37. json_array.append({
  38. 'id' : row[0],
  39. 'name' : row[1],
  40. 'category': row[2],
  41. 'description' : row[3]
  42. })
  43. # Send message back to client
  44. # Write content as utf-8 data
  45. message = json.dumps(json_array,ensure_ascii=False,indent=1)
  46. self.wfile.write(bytes(message, "utf8"))
  47. connection.close()
  48. return
  49.  
  50. server_address = ('127.0.0.1', 8080)
  51.  
  52. httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
  53.  
  54. print('Server has been started')
  55. httpd.serve_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement