簡體   English   中英

Cherrypy處理請求的方式有所不同

[英]Cherrypy handling requests differently

我試圖找出一種方法,需要在兩個不同的頁面上調用一個函數,並且該函數將根據調用的函數相應地處理請求。

該流既可以是基於調用函數的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)

我以前沒用過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

這就是我嘗試過對我有用的東西的方式。 我對函數本身使用了form動作。 這不能完全根據問題中提到的哪個函數調用另一個函數來處理,但是調用另一個函數的相同函數通過對自身使用form動作來處理自身。

    @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

暫無
暫無

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

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