简体   繁体   中英

Insert data into MYSQL Database by invoking python script through SimpleHTTPServer

I have the following python script.

import  mysql.connector

cnx = mysql.connector.connect(user='root', password = 'signal', host = '127.0.0.1', port = '1928'
                              ,
                              database = 's_events')
cursor = cnx.cursor()

insert_stmt =   "INSERT INTO t_events (eid)   VALUES ('iosevent123')"


data = 'iosevent123'
cursor.execute(insert_stmt)

cnx.commit()

cnx.close()

I also started a simplehttpserver provided by python.

How do I invoke the above script so that the data is inserted into the table?

Pulling from this example as inspiration, run a server on some machine by executing the python script [disclaimer: untested]

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

cnx = mysql.connector.connect(user='root', password = 'signal', host = '127.0.0.1', port = '1928'
                              ,
                              database = 's_events')
cursor = cnx.cursor()

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        self._set_headers()

        # Assuming the value to insert is just provided in the URL
        # path. e.g., "http://127.0.0.1/<val>"
        i_slash = self.path.index('/')
        val = self.path[(i_slash + 1):]
        insert(val)


def run(server_class=HTTPServer, handler_class=S, port=80):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print 'Starting httpd...'
    httpd.serve_forever()

def insert(val):
    cursor.execute("INSERT INTO t_events (eid) VALUES ('%s');" % val)

if __name__ == "__main__":
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

Once that's running, "simply" send a get request from the IOS app to the server you started. (I quoted "simply" because I have not worked with IOS, but would imagine that pinging APIs is commonplace.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM