簡體   English   中英

將簡單的Perl腳本翻譯成可向客戶端發送響應的Python?

[英]Translate simple Perl script into Python that sends a response to client?

我真的是Python新手,我的目標是讓Python腳本向客戶端打印一些內容,然后在網頁上顯示。

幸運的是,我偶然發現了一個很小的代碼片段,該片段完全可以實現我想用Python實現的功能-不幸的是,它是用Perl編寫的。

我想知道是否有人可以向我展示如何用Python編寫Perl腳本?

這是包含所有代碼的鏈接: http : //www.degraeve.com/reference/simple-ajax-example.php

這是Perl腳本:

#!/usr/bin/perl -w
use CGI;

$query = new CGI;

$secretword = $query->param('w');
$remotehost = $query->remote_host();

print $query->header;
print "<p>The secret word is <b>$secretword</b> and your IP is <b>$remotehost</b>.</p>";

我如何在Python中說同樣的話?

這也是HTML頁面:

<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">
function xmlhttpPost(strURL) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText);
        }
    }
    self.xmlHttpReq.send(getquerystring());
}

function getquerystring() {
    var form     = document.forms['f1'];
    var word = form.word.value;
    qstr = 'w=' + escape(word);  // NOTE: no '?' before querystring
    return qstr;
}

function updatepage(str){
    document.getElementById("result").innerHTML = str;
}
</script>
</head>
<body>
<form name="f1">
  <p>word: <input name="word" type="text">  
  <input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/cgi-bin/ajaxTest.pl")'></p>
  <div id="result"></div>
</form>
</body>
</html>

這樣的事情應該起作用。

#!/usr/bin/env python 

import cgi
import os
import cgitb; cgitb.enable()  # for troubleshooting

form = cgi.FieldStorage()
secretword = form.getfirst("w", "")
remotehost = cgi.escape(os.environ["REMOTE_HOST"] if "REMOTE_HOST" in os.environ else os.environ["REMOTE_ADDR"])

print "Content-Type: text/html"     
print # blank line, end of headers
print "<p>The secret word is <b>" + secretword + "</b> and your IP is <b>" + remotehost + "</b>.</p>"

編輯1:如何列出所有環境變量。

for k in os.environ.keys():
    print "<b>%20s</b>: %s<\br>" % (k, os.environ[k])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM