Python响应HTTP请求 [英] Python respond to HTTP Request

查看:618
本文介绍了Python响应HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些我认为非常简单的事情,但是由于我对Python相当陌生,所以我无法找到方法.调用URL时,我需要在Python脚本中执行一个函数.

I am trying to do something that I assume is very simple, but since I am fairly new to Python I haven't been able to find out how. I need to execute a function in my Python script when a URL is called.

例如,我将在浏览器中访问以下URL(192.168.0.10是运行脚本的计算机的IP,而8080是选择的端口).

For example, I would visit the following URL in my browser (192.168.0.10 being the IP of the computer I am running the script on, and 8080 being the port of choice).

http://192.168.0.10:8080/captureImage

访问此URL时,我想在我的Python脚本中执行一个操作,在这种情况下,执行我执行的功能.

When this URL is visited, I would like to perform an action in my Python script, in this case execute a function I made.

我知道这可能很简单,但是我无法找出如何做到这一点.我将不胜感激!

I know this might be fairly simple, but I haven't been able to find out how this can be done. I would appreciate any help!

推荐答案

在python中确实非常简单:

This is indeed very simple to do in python:

import SocketServer
from BaseHTTPServer import BaseHTTPRequestHandler

def some_function():
    print "some_function got called"

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/captureImage':
            # Insert your code here
            some_function()

        self.send_response(200)

httpd = SocketServer.TCPServer(("", 8080), MyHandler)
httpd.serve_forever()

根据您要从此处到达的位置,您可能要签出 BaseHttpServer ,或研究功能更全的Web框架,例如Django.

Depending on where you want to go from here, you might want to checkout the documentation for BaseHttpServer, or look into a more full featured web framework like Django.

这篇关于Python响应HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆