Cherrypy以不同的方式处理请求

2024-10-03 23:29:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出一种方法,我需要有两个不同的页面调用一个函数,函数将根据调用的函数相应地处理请求。在

流可以是基于调用函数的predict function句柄,也可以是它将值返回给调用函数,然后重新加载调用函数页以显示必须显示的结果。在

Class GSpam:

    @cherrypy.expose
    def main(self,contents=""):
        return call predict

    @cherrypy.expose
    def alt(self):
        return """<html>
        <div align=center>
          <body>
        <br>
        <br>
            <form method="post" action="predict">
              <input type="text" value="Enter post to check" name="text" />
              <button type="submit">Predict!</button>
            </form>
        </div>
          </body>
        </html>"""

    @cherrpy.expose
    def predict(self,text):
        do some stuff
        check which function called and return accordingly
        return result

if __name__ == '__main__':
    port = 80
    api = cherrypy.dispatch.RoutesDispatcher()
    api.connect('home','/',controller=GSpam,action='main')
    conf = {'/': {'request.dispatch': api}}
    cherrypy.config.update({
        'server.socket_host' : "0.0.0.0",
        'server.socket_port' : int(port),
        'server.thread_pool' : 10,
        'engine.autoreload.on' : False,
        'response.timeout' : 10
    })
    app=cherrypy.tree.mount(root=None,config=conf)

我以前没用过樱桃糖。感谢任何帮助。在


Tags: 函数textselfapireturnservermainport
2条回答

创建一个私有方法如何:

class GSpam:

   def _predict(self, text, from_='original'):
       if from_ == 'original':
          return "Something very different"
       else:
          return "Content for %s" % from_

   @cherrypy.expose
   def main(self,contents=""):
       return self._predict(contents, 'main')

   @cherrypy.expose
   def alt(self):
       return """<html>
       <div align=center>
         <body>
       <br>
       <br>
           <form method="post" action="predict">
            <input type="text" value="Enter post to check" name="text" />
            <button type="submit">Predict!</button>
           </form>
       </div>
         </body>
       </html>"""

   @cherrypy.expose
   def predict(self, text):
       #do some stuff
       result = self._predict(text)
       return result

下面是我如何尝试一些对我有用的方法。我在函数本身上使用了形式action。这并不能完全根据问题中提到的哪个函数调用另一个函数来处理,但是调用另一个函数的同一个函数通过对自身使用form action来处理自己。在

    @cherrypy.expose
        def index(self,text=""):

            cherrypy.response.headers['Content-Type'] = 'text/xml'
            try:
                if not text:
                    cherrypy.response.status = 400
                    return "<error>\n<code>400</code>\n<msg>empty text</msg>\n</error>"
                else:

                    res=self.predict(text)
                    res=[map(lambda x : "spam" if x==0 else "ham" ,res[0]),res[1]]
                    return '<?xml version="1.0"?><Result>\n<Logistic_Regression>\n<Label>'+res[0][1]+'</Label>\n<Score>'+str(res[1][1])+'</Score>\n</Logistic_Regression>\n<Linear_SVM>\n<Label>'+res[0][0]+'</Label>\n<Score>'+str(res[1][0])+'</Score>\n</Linear_SVM>\n<Random_Forest>\n<Label>'+res[0][2]+'</Label>\n<Score>'+str(res[1][2])+'</Score>\n</Random_Forest>\n</Result>' 

            except Exception, e:
                cherrypy.response.status = 500
                return "<error>\n<code>500</code>\n<msg>%s</msg>\n</error>" % traceback.format_exc()


        @cherrypy.expose
        def alt(self,text="",is_money=""):
            if text=="":
                return """<html>
                <div align=center>
                <h1>Spam Detector</h1>
                <title>Spam Detector</title>
                <body>
                <br>
                <form method="post" action="alt">
                <input type="text" value="" placeholder="Enter post to check" name="text" />
                <br><br>
                Is Money : <input type="radio" name="is_money" value="y" checked> Y<input type="radio" name="is_money" value="n">N
                &emsp;<button type="submit">Predict!</button>
                </form>
                </div>
                </body>
            </html>"""
            else:
                res=self.predict(text,is_money)
                res=[map(lambda x : "<font color='red'>spam" if x==0 else "<font color='green'>ham" ,res[0]),res[1]]
                print res
                text= text + "<br> #money" if is_money=="y" else text
                separator="<br><br><div align=center><hr width=50%></div><br><br>"
                htmlstart="""<html>
                <div align=center>
                <h1>Spam Detector</h1>
                <title>Spam Detector</title>
                <body>
                <br>
                <br>
                <form method="post" action="alt">
                <input type="text" value="" placeholder="Enter post to check" name="text" />
                <br>
                Is Money : <input type="radio" name="is_money" value="y" checked> Y<input type="radio" name="is_money" value="n">N
                <button type="submit">Predict!</button>
                </form>
                </div><div align=center>"""+separator
                htmlend="</body></html>"
                html="<b><table border=0 style='width:60%' cellspacing=20  ><tr><td align='center' valign='middle'><font color = 'navy'><b>Logistic Regression</td><td></td><td align='center' valign='middle'><b><font color='navy'>Linear SVM</b></font></td><td></td><td align='center' valign='middle'><b><font color='navy'>Random Forest</b></font></td></tr><tr><td align='center' valign='middle'><h1>"+res[0][1]+"</font></h1></td><td></td><td align='center' valign='middle'><h1>"+res[0][0]+"</font></h1></td><td></td><td align='center' valign='middle'><h1>"+res[0][2]+"</font></h1></td></tr><tr><td align='center' valign='middle' colspan=5><font color='orangered'><b>Text : <font color='orange'>"+text+"</td></tr><tr><td align='center' valign='middle'><font color='navy'><b>Probability : <font color='blue'>"+str(res[1][1])+"</b></td><td></td><td align='center' valign='middle'><b><font color='navy'>Probability : <font color='blue'>"+str(res[1][0])+"</font></b></td><td></td><td align='center' valign='middle'><font color='navy'><b>Probability : <font color='blue'>"+str(res[1][2])+"</b></td></tr></table>"
                if 'html' not in cherrypy.session:
                    cherrypy.session['html']=[html]
                else:
                    li=cherrypy.session['html']
                    li.append(html)
                    cherrypy.session['html']=li[-5:]
                txt=separator.join((cherrypy.session['html'])[::-1])
                return htmlstart+txt+htmlend
def predict(self,text="",is_money=""):
     return do_Something

相关问题 更多 >