簡體   English   中英

未在 CGI 腳本中應用 CSS

[英]CSS not being applied in CGI script

我寫了這個 cgi 腳本

#!/usr/bin/env python

import cgi


print "Content-type: text/html\n\n"
print"<html>"
print"<title>Wedmed Search engine</title>"
print"""<link type="text/css" rel="stylesheet" href="stylesheet1.css"/>
<body>

<div class="img" position="center">
    <h1>
        WebMED</h1>
    </div>

<form action="/cgi-bin/hello.py" method="POST">

    <input type="text" size="50" name="data" value=""><br>

    <input type="submit" value="Submit">  
    <input type="reset" value="Reset">

</form>
</body></html>"""

問題是 css 不適用於我的 cgi 腳本。 它適用於 html 代碼。 有人可以幫忙嗎??

我想這是相對/絕對尋址的問題。 嘗試將絕對地址設置為您的 css 文件。

如果服務器上的文件結構是

/css
    /stylesheet1.css 

那么href將是“/css/stylesheet1.css”

或者如果 stylesheet1.css 直接在 htdocs 中,那么 href 將是“/stylesheet1.css”

如果python腳本和css文件在同一個目錄下,試試這個:

<link type="text/css" rel="stylesheet" href="/stylesheet.css" />

在提及 css 文件的位置之前添加“/”很重要。

在類似的情況下,我通過以下方式更改了代碼:

...
print "Content-type: text/html\n\n"
print"<html>"
...

...
print "Content-type: text/html\n\n"
print ""
print"<html>"
...

同樣在我的情況下,我使用了另一種形式的印刷品

...
print("Content-type: text/html")
print("")
print("<html>")
...

我找到了一種不是最好的方法,但對我有用。

把你的整個樣式表放在stylesheet1.css就像你已經做的那樣,然后把它寫在你的 python 文件中

f = open('stylesheet1.css', 'r')
style = ''
for i in f:
    style += i
head = '''
    <head>
    <style>
    %s
    <style>
    </head>''' % (style)
print "Content-type: text/html\n\n"
print"<html>"
print head
print """<body>

<div class="img" position="center">
    <h1>
        WebMED</h1>
    </div>

<form action="/cgi-bin/hello.py" method="POST">

    <input type="text" size="50" name="data" value=""><br>

    <input type="submit" value="Submit">  
    <input type="reset" value="Reset">

</form>
</body></html>"""

這是一個路徑和隱私問題。 將您的 *.css 放在 html 目錄 (/var/www/html) 中,而不是 ./cgi-bin。 在這種情況下,網址應如下所示: href="/stylesheet.css"

首先,在你的代碼中,如果你想在python cgi中使用css,你可以添加head。

其次,您可能需要確保配置正確,即您使用的服務器。

下面是一個簡單的 hello.py 示例,即

#!/usr/bin/python

html ="""Content-type:text/html\r\n\r\n
<html>
<head>
<link type="text/css" rel="stylesheet" href="styles.css" />
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>"""
print html

例子中使用的是apache,結構為,

# ls /var/www/cgi-bin
-rwxr-xr-x 1 root root 263 Nov  4 05:55 hello.py
-rwxr-xr-x 1 root root  83 Nov  4 06:38 styles.css

因此,需要在httpd.conf啟用 css

ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
<Directory "/var/www/cgi-bin">
    AddHandler default-handler .css
    AllowOverride None
    Options None
    Require all granted
</Directory>

最后,你應該能夠看到,

在此處輸入圖片說明

那是因為css,即

body {
  background-color: powderblue;
}
h1 {
  color: blue;
}
p {
  color: red;
}

暫無
暫無

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

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