gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:00:14 25 4
gpt4 key购买 nike

我有以下 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。

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

最佳答案

取自 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,但我想 ping API 是很常见的。)

关于python - 通过SimpleHTTPServer调用python脚本将数据插入MYSQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42403206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com