Cherrypy 处理请求的方式不同

Cherrypy handling requests differently

我想找出一种方法,让两个不同的页面调用一个函数,该函数将根据调用的函数相应地处理请求。

流程可以是基于调用函数的 predict function 句柄,或者它将 return 一个值传递给调用函数,然后调用函数页面重新加载以显示结果必须显示。

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)

我以前没有用过cherrypy。感谢任何帮助。

如何创建一个私有方法:

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

以下是我尝试对我有用的方法的方法。我在函数本身上使用了表单操作。这并不完全基于问题中提到的哪个函数调用另一个函数来处理,而是调用另一个函数的同一函数通过对自身使用表单操作来处理自身。

    @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