[英]Replace webapp2 usage for self.response.write in python script
我是python的新手,並且開始通過在google app引擎上創建一個簡單的應用程序開始工作,但是現在我想將其部署到其他地方。 (我知道我可以在非appengine python環境中安裝webapp2,但目前不願意。)
如何更改以下python代碼,使其執行相同的操作但沒有webapp2?
import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
self.response.write('<a href="index.html">Search</a>')
app = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
我已經嘗試過使用print命令,urllib,重定向,甚至考慮編寫腳本來編寫基本的Web服務器,但是這些都不起作用,或者看起來像是過大了。
我正在嘗試建立一個非常基本的python控制/創建的歡迎頁面,並帶有一個指向我的單頁網站index.html的鏈接。
我目前正在使用Cloud9,該服務器運行Apache Web服務器,如果python腳本不起作用,該服務器將加載index.html。 但是,在開始將整個內容轉換為完整的Flask或Django應用程序之前,我更喜歡以這種簡單的方式來運行python腳本。
任何幫助或提示,不勝感激。
最終pythonanywhere通過WSGI給了我所需的東西,結果很簡單:
SEARCH = """<html>
<head></head>
<body>
<div style="text-align: center; padding-left: 50px; padding-top: 50px; font-size: 1.75em;">
<p>Welcome:</p><a href="index.html">Search</a>
</div>
</body>
</html>
"""
def application(environ, start_response):
if environ.get('PATH_INFO') == '/':
status = '200 OK'
content = SEARCH
else:
status = '404 NOT FOUND'
content = 'Page not found.'
response_headers = [('Content-Type', 'text/html'), ('Content-Length', str(len(content)))]
start_response(status, response_headers)
yield content.encode('utf8')
如果您的目標是僅使用內置模塊來處理基本請求,則可以查找BaseHTTPServer和相關類。 這是一個簡單的示例:
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
PORT_NUMBER = 8080
class myHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write('<a href="index.html">Search</a>')
return
try:
server = HTTPServer(('', PORT_NUMBER), myHandler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
請注意,默認情況下,這不會提供靜態文件,但您應該能夠添加多個處理程序。 也許可以查找: https : //docs.python.org/2/library/simplehttpserver.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.