通过simplehtp调用python脚本将数据插入MYSQL数据库

2024-06-08 16:12:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的python脚本。在

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()

我还启动了python提供的simplehttpserver。在

如何调用上面的脚本以便将数据插入表中?在


Tags: import脚本connectorsignalconnectmysqlrootpassword
1条回答
网友
1楼 · 发布于 2024-06-08 16:12:02

this example为灵感,通过执行python脚本[免责声明:未测试]在某些计算机上运行服务器

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()

一旦运行,只需从IOS应用程序向启动的服务器发送get请求。(我引用“简单”是因为我没有使用过IOS,但我认为pingapi是很常见的。)

相关问题 更多 >