【问题标题】:Insert data into MYSQL Database by invoking python script through SimpleHTTPServer通过 SimpleHTTPServer 调用 python 脚本将数据插入 MYSQL 数据库
【发布时间】:2017-02-22 22:07:04
【问题描述】:

我有以下 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提供的简单httpserver。

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

【问题讨论】:

  • 呃,python name_of_script.py 在终端?还是你在问别的?
  • @heyiamt 我知道如何在终端中运行它。我想从 IOS 应用程序调用像 localhost:1222/a.py 这样的 URL 并将数据插入到表中。这可能吗?
  • 明白了。很抱歉对于这个误会。我认为您需要做一些事情like this,其中服务器充当 Web API。然后,IOS 应用程序将向服务器发送一个请求,其中包含使用脚本中的代码触发函数的指令。
  • 我不太明白你的意思。启动最小的http服务器后,我该怎么办?

标签: python mysql web-services simplehttpserver


【解决方案1】:

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 应用程序向您启动的服务器发送一个获取请求。 (我引用“简单”是因为我没有使用过 IOS,但可以想象 ping API 是司空见惯的。)

【讨论】:

  • 它正在工作,尽管它在表中插入了一个带有值 favicon.ico 的附加行。知道是什么原因造成的吗?
  • 将我们插入数据库的值作为通过 URL 传递的参数是最佳实践吗?我还有什么其他选择?
  • @adf_mobile_devoper re: favicon.ico - 该字符串必须以某种方式通过请求中发送的刺痛进入。也许尝试抓住获取请求字符串来找出答案?
  • @adf_mobile_developer re:基于 https 消息的数据库插入 - 我同意这可能不是一个很好的解决方案,特别是如果我插入了敏感或 PII 日期。要做的事情是对正在传递的消息进行一些加密,但这不是我以前做过的事情。
猜你喜欢
  • 1970-01-01
  • 2012-04-19
  • 2014-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-23
相关资源
最近更新 更多