Skip to content

Instantly share code, notes, and snippets.

@thblckjkr
Created April 28, 2021 05:05
Show Gist options
  • Save thblckjkr/4954ef9fd635f3f804d57c7834b9cb97 to your computer and use it in GitHub Desktop.
Save thblckjkr/4954ef9fd635f3f804d57c7834b9cb97 to your computer and use it in GitHub Desktop.
Simple MySQL API

Prueba de que es posible realizar un servidor HTTP en python, sin utilizar Apache, Nginx o similares.

Sólamente utilizando un script de python, que incluye las librerías BaseHTTPRequestHandler y HTTPServer

Para correrlo, crear la base de datos correspondiente adjunta, y correr el script así

./server.py o python server.py

Nota: Requiere de Python3

Ejemplo de funcionamiento:

./server.py
Starting httpd...

# en esta parte se realiza un request a la dirección 127.0.0.1:8080 en el navegador

127.0.0.1 - - [27/Apr/2021 22:59:19] "GET / HTTP/1.1" 200 -

# Respuesta en el navegador
[{"id": 1, "nombre": "TEST"}, {"id": 2, "nombre": "Otro Test"}]
CREATE database `test`;
CREATE TABLE `test`.`test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO test VALUES
( 1, 'TEST' ),
(2, 'Otro TESt')
#!/usr/bin/env python3
"""
Very simple HTTP server in python for making requests to a database and returning them as a json array
Usage::
./server.py [<port>]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import pymysql.cursors
import json
class DB:
def __init__(self):
self.conn = pymysql.connect(
host = '127.0.0.1',
user = 'root',
passwd = 'root'
)
def query(self):
response = []
sql = 'SELECT * FROM test.test'
with self.conn.cursor() as cursor:
cursor.execute(sql)
while True:
row = cursor.fetchone()
# If EOF break
if row == None:
break
response.append({ 'id': row[0], 'nombre': row[1] })
return response
class S(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
def do_GET(self):
db = DB()
data = db.query()
self._set_response()
self.wfile.write(bytes(json.dumps(data),"utf-8"))
def run(server_class=HTTPServer, handler_class=S, port=8080):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print('Starting httpd...\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print('Stopping httpd...\n')
if __name__ == '__main__':
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment