首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python,发布BaseHTTPServer和GET

Python,发布BaseHTTPServer和GET
EN

Stack Overflow用户
提问于 2015-03-02 10:35:22
回答 2查看 1.4K关注 0票数 0

我正在制作一个非常简单的应用程序,目前在URL下有两个网页:localhost:8080/餐馆/和localhost:8080/高速路/新的。我有一个sqlite数据库,我在python代码中使用SQLAlchemy来操作它。

在我的第一页localhost:8080/ page /上,它只包含我的数据库中可用的餐馆列表。我的第二页localhost:8080/高速路/新的,在这里我有一个表单,以便一个新的餐厅,它显示在本地主机:8080/餐馆。但是,每当我在localhost的表单上输入一个新的餐馆名称:8080/餐馆/新建时,它都不能将我重定向回本地主机:8080/餐馆/为了向我显示新的餐厅,它只是停留在相同的url链接localhost:8080/restaurants/new上,并带有“没有收到数据”的消息。下面是我的代码:

代码语言:javascript
复制
import cgi
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

#import libraries and modules
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem

#create and connect to database
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind=engine
DBSession = sessionmaker(bind=engine)
session = DBSession()


class webServerHandler(BaseHTTPRequestHandler):
    """ class defined in the main method"""

    def do_GET(self):
        try:
            #look for url then ends with '/hello'
            if self.path.endswith("/restaurants"):
                self.send_response(200)

                #indicate reply in form of html to the client
                self.send_header('Content-type', 'text/html')

                #indicates end of https headers in the response
                self.end_headers()

                #obtain all restaurant names from databse
                restaurants = session.query(Restaurant).all()

                output = ""
                output += "<html><body><a href='/restaurants/new'>Add A New Restaurant</a>"
                output += "</br></br>"

                for restaurant in restaurants:
                    output += restaurant.name
                    output += """<div>
                            <a href='#'>Edit</a>
                            <a href='#'>Delete</a>
                            </div>"""
                    output += "</br></br>"
                output += "</body></html>"

                self.wfile.write(output)
                print output
                return


            if self.path.endswith("/restaurants/new"):
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()

                output = ""
                output += "<html><body>"
                output += "<h1>Add New Restaurant</h1>"

                output += "<form method='POST' enctype='multipart/form-data action='/restaurants/new'>"
                output += "<input name='newRestaurant' type='text' placeholder='New Restaurant Name'>"
                output += "<input name='Create' type='submit' label='Create'>"
                output += "</form></body></html>"

                self.wfile.write(output)
                return

        except IOError:

            self.send_error(404, "File %s not found" % self.path)



    def do_POST(self):

        try:
            if self.path.endswith("/restaurants/new"):

                ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))

                #check of content-type is form
                if ctype == 'mulitpart/form-data':

                    #collect all fields from form, fields is a dictionary
                    fields = cgi.parse_multipart(self.rfile, pdict)

                    #extract the name of the restaurant from the form
                    messagecontent = fields.get('newRestaurant')

                    #create the new object
                    newRestaurantName = Restaurant(name = messagecontent[0])
                    session.add(newRestaurantName)
                    session.commit()

                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location','/restaurants')
                    self.end_headers()

        except:
            pass




def main():
    """An instance of HTTPServer is created in the main method 
    HTTPServer is built off of a TCP server indicating the 
    transmission protocol
    """
    try:
        port = 8080

        #server address is tuple & contains host and port number
        #host is an empty string in this case
        server = HTTPServer(('', port), webServerHandler)


        print "Web server running on port %s"  % port

        #keep server continually listening until interrupt occurs
        server.serve_forever()


    except KeyboardInterrupt:
        print "^C entered, stopping web server...."

        #shut down server
        server.socket.close()


#run main method
if __name__ == '__main__':
    main()

下面是我创建数据库的database_setup文件,以供参考:

代码语言:javascript
复制
import sys

#importing classes from sqlalchemy module
from sqlalchemy import Column, ForeignKey, Integer, String

#delcaritive_base , used in the configuration
# and class code, used when writing mapper
from sqlalchemy.ext.declarative import declarative_base

#relationship in order to create foreign key relationship
#used when writing the mapper
from sqlalchemy.orm import relationship

#create_engine to used in the configuration code at the
#end of the file
from sqlalchemy import create_engine


#this object will help set up when writing the class code
Base = declarative_base()



class Restaurant(Base):
    """
    class Restaurant corresponds to restaurant table
    in the database to be created.

    table representation for restaurant which
    is in the database 
    """
    __tablename__ = 'restaurant'


    #column definitions for the restaurant table
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)



class MenuItem(Base):
    """
    class MenuItem corresponds to restaurant table


    table representation for menu_item which
    is in the database      
    """
    __tablename__ = 'menu_item'

    #column definitions for the restaurant table
    name = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    course = Column(String(250))
    description = Column(String(250))
    price = Column(String(8))
    restaurant_id = Column(Integer, ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant)



#create an instance of create_engine class
#and point to the database to be used
engine = create_engine(
    'sqlite:///restaurantmenu.db')


#that will soon be added into the database. makes
#the engine
Base.metadata.create_all(engine)

我不明白为什么我不能添加新的补充剂

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-08-27 00:28:00

我知道这是很久以前的事了,但我发现了你的问题。首先,在enctype='multipart/form-data'部分下的do_GET函数中的if self.path.endswith("/restaurants/new"):缺少最后一个单引号。第二,您在if ctype == 'multipart/form-data':中拼写错了“多部分”。希望能帮助你或其他人。

票数 1
EN

Stack Overflow用户

发布于 2018-05-12 00:52:20

正如切特文所说,问题在于表格中的加密类型。

由于漏掉了引号,“Content”改为“application/x form-urlencoded”,因此在这种情况下,您应该解析它,因为它是一个字符串。

为了管理这两种封装类型,您可以按以下方式修改do_POST

代码语言:javascript
复制
def do_POST(self):

    try:

        if self.path.endswith("/restaurants/new"):

            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))

            print ctype

            #check of content-type is form
            if (ctype == 'multipart/form-data') or (ctype == 'application/x-www-form-urlencoded'):

                #collect all fields from form, fields is a dictionary
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                else:
                    content_length = self.headers.getheaders('Content-length')
                    length = int(content_length[0])
                    body = self.rfile.read(length)
                    fields = urlparse.parse_qs(body)

                #extract the name of the restaurant from the form
                messagecontent = fields.get('newRestaurant')

                #create the new object
                newRestaurantName = Restaurant(name = messagecontent[0])
                session.add(newRestaurantName)
                session.commit()

                self.send_response(301)
                self.send_header('Location','/restaurants')
                self.end_headers()
                return

希望这个额外的信息对你有用!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28807659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档