简体   繁体   English

如何将python文件拆分为python和html文件

[英]how to split python file into python and html file

I am trying to make a python file into a python and html files. 我试图将python文件变成python和html文件。 The code i have is basically from the python guestbook example but i want to have a html file serve the uses browser. 我的代码基本上来自python留言簿示例,但我希望有一个html文件服务使用浏览器。 the code i have works right now but when i add the javascript at the bottom i get an error This code is at ceemee11111.appspot.com 我现在的代码工作,但当我在底部添加javascript我得到一个错误此代码在ceemee11111.appspot.com

import cgi
import datetime
import urllib
import webapp2

from google.appengine.ext import db
from google.appengine.api import users


class Greeting(db.Model):
  """Models an individual Guestbook entry with an author, content, and date."""
  author = db.StringProperty()
  content = db.StringProperty(multiline=True)
  content2 = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)


def guestbook_key(guestbook_name=None):
  """Constructs a Datastore key for a Guestbook entity with guestbook_name."""
  return db.Key.from_path('Guestbook', guestbook_name or 'default_guestbook')


class MainPage(webapp2.RequestHandler):
  def get(self):
    self.response.out.write('<html><body>')
    guestbook_name=self.request.get('guestbook_name')


    greetings = db.GqlQuery("SELECT * "
                        "FROM Greeting "
                        "WHERE ANCESTOR IS :1 "
                        "ORDER BY date DESC LIMIT 3",
                        guestbook_key(guestbook_name))


    self.response.out.write("""
      <form action="/sign?%s" method="post">
        <div id="container" style="width:800px">

        <div id="header" style="background-color:#FFA500;">
        <h1 style="margin-bttom:0;">Main Title</h1></div>

        <div id="Con0" style="background-color:#FFD700;
   height:200px;width:200px;float:left;">
         <b>Menu</b><br>
         HTML<br>
         CSS<br>
         <p id="demo1"></p><br>
         JavaScript</div>

       <div id="content" style="background-color:#EEEEEE;height:200px;width:600px;float:left;">
Content goes here</div>
      </div>
      <button onclick="myFunction()">Try it</button>
      </form>
    </body>
  </html>""") 


self.response.out.write("""
      <form action="/sign?%s" method="post">
       <div id="dataImput"
        <div><textarea name="content" rows="1" cols="10"></textarea></div>
        <div><textarea name="content2" rows="1" cols="10"></textarea></div>
        <div><input type="submit" value="Sign Guestbook"></div>
      </div>
      </form>
      <hr>
      <form>Guestbook name: <input value="%s" name="guestbook_name">
      <input type="submit" value="switch"></form>
    </body>
  </html>""" % (urllib.urlencode({'guestbook_name': guestbook_name}),
                      cgi.escape(guestbook_name)))


class Guestbook(webapp2.RequestHandler):
  def post(self):
    # We set the same parent key on the 'Greeting' to ensure each greeting is in
    # the same entity group. Queries across the single entity group will be
    # consistent. However, the write rate to a single entity group should
    # be limited to ~1/second.
    guestbook_name = self.request.get('guestbook_name')
    greeting = Greeting(parent=guestbook_key(guestbook_name))

    if users.get_current_user():
      greeting.author = users.get_current_user().nickname()

greeting.content = self.request.get('content')
greeting.content2 = self.request.get('content2')
greeting.put()
self.redirect('/?' + urllib.urlencode({'guestbook_name': guestbook_name}))


app = webapp2.WSGIApplication([('/', MainPage),
                           ('/sign', Guestbook)],
                          debug=True)

#<script>
#function myFunction()
#{
#document.getElementById("demo1").innerHTML="test";
#}

Thankyou for your time. 感谢您的时间。 Dan

I think your code will really benefit from separating the HTML from the Python code. 我认为您的代码将真正受益于将HTML与Python代码分离。

You can do that by writing an html template and use jinja2 (which comes with google appengine) to generate the html. 您可以通过编写html模板并使用jinja2(随google appengine附带)生成html来实现。 There are instructions on how to do that here . 这里有关于如何做到这一点的说明 The JavaScript would go in the HTML template, not in the Python code. JavaScript将放在HTML模板中,而不是Python代码中。

Given that you're clearly using GAE, what you are looking to do is outlined here . 鉴于您明确使用GAE, 此处概述了您要做的事情。

First, move your html to separate files. 首先,将您的html移动到单独的文件。 We'll start with the html from the oddly freefloating self.response.out.write : 我们将从奇怪的freefloating self.response.out.write的html开始:

"""
      <form action="/sign?%s" method="post">
       <div id="dataImput"
        <div><textarea name="content" rows="1" cols="10"></textarea></div>
        <div><textarea name="content2" rows="1" cols="10"></textarea></div>
        <div><input type="submit" value="Sign Guestbook"></div>
      </div>
      </form>
      <hr>
      <form>Guestbook name: <input value="%s" name="guestbook_name">
      <input type="submit" value="switch"></form>
    </body>
  </html>""" % (urllib.urlencode({'guestbook_name': guestbook_name}),
                      cgi.escape(guestbook_name))

This belongs in a separate file we'll call myhtml.html . 这属于一个单独的文件,我们称之为myhtml.html Second, we then are going to go through and using the Django templating system instead of %s and Python string formatting. 其次,我们将使用Django模板系统而不是%s和Python字符串格式。 So first, we're going to replace the %s with template-friendly fields surrounded by {{ }} , giving us: 首先,我们将用{{ }}包围的模板友好字段替换%s ,为我们提供:

"""
      <form action="/sign?{{ guestbook_name }}" method="post">
       <div id="dataImput"
        <div><textarea name="content" rows="1" cols="10"></textarea></div>
        <div><textarea name="content2" rows="1" cols="10"></textarea></div>
        <div><input type="submit" value="Sign Guestbook"></div>
      </div>
      </form>
      <hr>
      <form>Guestbook name: <input value="{{ guestbook_name|escape }}" name="guestbook_name">
      <input type="submit" value="switch"></form>
    </body>
  </html>"""

Note that we were able to use the escape template filter , which is what comes after the | 请注意,我们能够使用escape 模板过滤器 ,这是|之后的内容 , to escape the value we're getting from guestbook_name . ,以逃避我们从guestbook_name获得的价值。

Finally, we load the html and pass it the arguments we need: 最后,我们加载html并将它传递给我们需要的参数:

self.response.out.write(template.render('myhtml.html', {'guestbook_name': guestbook_name}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM