2013-02-28 217 views
4

我需要從Python中的文本文件中讀取一個url鏈接作爲變量,並在html中使用它。 文本文件「file.txt」,但只包含一個行「http://188.xxx.xxx.xx:8878」,此行應該被保存在變量「鏈接」,那麼我應該使用包含在HTML這個變量的,所以該鏈接,應打開時我點擊按鈕圖像「go_online.png」。我試圖改變我的代碼如下,但它不工作!請幫忙嗎?如何將python變量傳遞給html變量?

#!/usr/bin/python 
import cherrypy 
import os.path 
from auth import AuthController, require, member_of, name_is 
class Server(object): 
    _cp_config = { 
     'tools.sessions.on': True, 
     'tools.auth.on': True 
    } 
    auth = AuthController()  
    @cherrypy.expose 
    @require() 
    def index(self): 
     f = open ("file.txt","r") 
     link = f.read() 
     print link 
     f.close() 
     html = """ 
     <html> 
     <script language="javascript" type="text/javascript"> 
      var var_link = '{{ link }}'; 
     </script> 
      <body> 
      <p>{htmlText} 
      <p>   
      <a href={{ var_link }} ><img src="images/go_online.png"></a> 
      </body> 
     </html> 
      """ 

     myText = ''   
     myText = "Hellow World"   
     return html.format(htmlText=myText) 
    index.exposed = True 

#configuration 
conf = { 
    'global' : { 
     'server.socket_host': '0.0.0.0', #0.0.0.0 or specific IP 
     'server.socket_port': 8085 #server port 
    }, 

    '/images': { #images served as static files 
     'tools.staticdir.on': True, 
     'tools.staticdir.dir': os.path.abspath('/home/ubuntu/webserver/images') 
    } 
    } 
cherrypy.quickstart(Server(), config=conf) 
+0

什麼網頁將是URL決心? – Makoto 2013-02-28 14:09:47

+0

的URL是我的服務器,它的我與開放端口的外部地址。 – Linux 2013-02-28 14:16:59

+0

URL可以是也可以是任何網頁,如www.google.com,......等等。 – Linux 2013-02-28 14:23:58

回答

3

第一關,不知道的JavaScript部分使任何意義,只是離開它。此外,您打開一個p標籤但不關閉它。不確定你的模板引擎是什麼,但你可以傳入純Python中的變量。另外,請確保將鏈接放在引號中。所以,你的代碼應該是這樣的:。

class Server(object): 
    _cp_config = { 
     'tools.sessions.on': True, 
     'tools.auth.on': True 
    } 
    auth = AuthController()  
    @cherrypy.expose 
    @require() 
    def index(self): 
     f = open ("file.txt","r") 
     link = f.read() 
     f.close() 
     myText = "Hello World" 
     html = """ 
     <html> 
      <body> 
       <p>%s</p>   
       <a href="%s" ><img src="images/go_online.png"></a> 
      </body> 
     </html> 
     """ %(myText, link)   
     return html 
    index.exposed = True 

(順便說一句,在%s的東西都串佔位符,將在多行字符串的結尾poplulated的變量%(firstString,secondString)

+0

感謝您的回覆,不過比較遺憾的是不幹活,返回html.format嘗試(的htmlText會將myText =,鏈接),但不行!你可以請重寫全部代碼? – Linux 2013-02-28 15:04:50

+0

更新我的回答,希望這有助於 – Hoff 2013-02-28 15:36:47

+0

感謝霍夫,它的工作現在。在我原來的鱈魚,變量「myText =''」將有一個新的字符串值根據一些「如果」的條件,所以我必須使用「返回html.format(htmlText = myText) 「。所以有另一種解決方案,讓我使用return html.format(htmlText = myText)? – Linux 2013-02-28 16:17:01