2013-10-17 45 views
10

我正在嘗試做一些我認爲非常簡單的事情,但由於我對Python相當陌生,因此我一直無法找出如何做到。我需要在調用URL時在我的Python腳本中執行一個函數。例如,我將在瀏覽器中訪問以下URL(192.168.0.10是我正在運行腳本的計算機的IP,而8080是所選端口)。Python對HTTP請求作出響應

http://192.168.0.10:8080/captureImage 

當訪問這個URL,我想在我的Python腳本執行的操作,在這種情況下執行我做了一個功能。

我知道這可能相當簡單,但我一直無法找出如何做到這一點。我將不勝感激任何幫助!

+0

首先,你需要一個web服務器。您是否已經安裝並在該計算機上運行了Web服務器? –

+0

如果你使用Windows這個鏈接可能工作http://stackoverflow.com/questions/3179657/python-webbrowser-question –

+0

我想你誤解了我。我希望Python腳本充當某種Web服務器,除非我不需要提供任何文件。當客戶端訪問服務器上的URL時,我需要能夠執行一個函數。 – Lazze

回答

7

這確實是很簡單的蟒蛇做:

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。

+0

這正是我正在尋找的,謝謝! 但是,我遇到了另一個問題。當我用你的代碼啓動腳本時,Web服務器會停止腳本的其餘部分執行。這是一個問題,因爲我需要在調用URL時從腳本執行一個函數。我將如何去解決這個問題? – Lazze

+0

@Lazze - 我更新了示例以包含函數調用,這有幫助嗎?爲了澄清,您希望Web服務器只處理一個請求然後關閉的問題?或者是從未運行的httpd.serve_forever()行之後存在代碼的問題? (在這種情況下,您可以將httd.server_forever()行向下移動到腳本末尾) –

+0

在serve_forever()之後永遠不會運行代碼。當我回家時,我會嘗試將其移到我的腳本的底部,並將回報。感謝您迄今的幫助! – Lazze

-1

完成你所需要的一種強有力的方法是使用Python Web框架Flask(http://flask.pocoo.org/)。有Youtube視頻可以很好地解釋Flask的基礎知識(https://www.youtube.com/watch?v=ZVGwqnjOKjk)。

下面是我的動作探測器的一個例子,當我的貓在門口等待時,它給我發短信。所有需要做的事情都是爲了在這個地址發送HTTP請求(在我的情況下)http://192.168.1.112:5000/cat_detected

from flask import Flask 
    import smtplib 
    import time 


    def email(from_address, to_address, email_subject, email_message): 
     server = smtplib.SMTP('smtp.gmail.com:587') 
     server.ehlo() 
     server.starttls() 
     server.login(username, password) 
     # For character type new-lines, change the header to read: "Content-Type: text/plain". Use the double \r\n. 
     # For HTML style tags for your new-lines, change the header to read: "Content-Type: text/html". Use line-breaks <br>. 
     headers = "\r\n".join(["from: " + from_address, "subject: " + email_subject, 
         "to: " + to_address, 
         "mime-version: 1.0", 
         "content-type: text/plain"]) 
     message = headers + '\r\n' + email_message 
     server.sendmail(from_address, to_address, message) 
     server.quit() 
     return time.strftime('%Y-%m-%d, %H:%M:%S') 


    app = Flask(__name__) 


    @app.route('/cat_detected', methods=['GET']) 
    def cat_detected(): 
     fromaddr = 'CAT ALERT' 
     admin_addrs_list = [['[email protected]', 'Mark']] # Use your carrier's format for sending text messages via email. 
     for y in admin_addrs_list: 
      email(fromaddr, y[0], 'CAT ALERT', 'Carbon life-form standing by the door.') 
     print('Email on its way!', time.strftime('%Y-%m-%d, %H:%M:%S')) 
     return 'Email Sent!' 

    if __name__ == '__main__': 
     username = '[email protected]' 
     password = 'yourGmailPassword' 
     app.run(host='0.0.0.0', threaded=True)