Cherrypy不公开方法

时间:2015-08-04 23:48:36

标签: jquery python cherrypy

我的代码如下:

import cherrypy as cp
import numpy as np
import pandas as pd
import os
import simplejson
import sys
import operator
global pagearray
global timearray
global state
timearray = np.load("buyertimearray.npy")
pagearray = np.load("buyerpagearray.npy")
state = "All"
MAX_WEBSITES = 10
DIR = os.path.abspath(".")

class Main(object):
    @cp.expose
    def index(self):
        return open(os.path.join(DIR+"/client/", 'index.html'))

    @cp.expose
    def refresh(self, starttime, endtime):
        global pagearray
        global timearray
        starttime = int(starttime)
        endtime = int(endtime)
        if state == "Buyers":
            pagearray = np.load("buyerpagearray.npy")
        elif state == "All":
            pagearray = np.load("allpagearray.npy")
        newpagearray =[]
        for i in np.argsort(timearray):
            newpagearray += [pagearray[i]]
        pagearray = newpagearray
        timearraysorted = np.sort(timearray)
        i=1
        startindex = 0
        endindex = 0
        while len(timearraysorted)-1 > i and starttime > int(timearraysorted[i]):
             startindex = i
             i+=1
        while len(timearraysorted)-1 > i and endtime > int(timearraysorted[i]):
             endindex = i
             i+=1
        pagearray = pagearray[startindex:endindex]

        startingpages = []
        if not pagearray:
            returnvaluelist = []
            weight = []
        else:
            for i in pagearray:
                if(i):
                    startingpages+=[i[0]]
            x = build_dict(startingpages)
            sorted_x = sorted(x.items(), key=operator.itemgetter(1), reverse=True)
            totalelements = len(pagearray)
            returnvaluelist = []
            weight = []
            for i in sorted_x:
                returnvaluelist += [i[0]]
                weight += [(i[1]/(totalelements*1.0))*100]
        return simplejson.dumps({"startingvalues":returnvaluelist, "weight":weight})

    @cp.expose
    def initialize(self):
        global pagearray
        global timearray
        global state
        pagearray = np.load("allpagearray.npy")
        timearray = np.load("alltimearray.npy")
        state = "All"
        firstwebsites = []
        firstwebsitepercentage = []
        totalvisitsfirst = np.sum(first)
        lastwebsites = []
        lastwebsitepercentage = []
        totalvisitslast = np.sum(last)
        for i in sorted_first[-49:]:
            firstwebsites += [vs.site[i]]
            firstwebsitepercentage += [(first[i]/totalvisitsfirst)*100]
        for i in sorted_last[-49:]:
            lastwebsites += [vs.site[i]]
            lastwebsitepercentage += [(last[i]/totalvisitsfirst)*100]
        return simplejson.dumps({"firstID":sorted_first[-49:].tolist(), "firstWebsites":firstwebsites, "firstPercentage":firstwebsitepercentage, "lastID":sorted_last[-49:].tolist(), "lastWebsites":lastwebsites, "lastPercentage":lastwebsitepercentage})

    @cp.expose
    def getPopLinks(self, siteId, direction):
        websiteArray = []
        siteId = float(siteId)
        if direction == "forward":
            rawcolumn = freq[:,siteId]
            sorted_column = np.argsort(freq[:,siteId])
        if direction == "backward":
            rawcolumn = freq[siteId,:]
            sorted_column = np.argsort(freq[siteId,:])
        websiteIDArray = sorted_column[-49:]
        sum_raw = np.sum(rawcolumn)
        percentages = []
        for i in websiteIDArray:
            percentages += [(rawcolumn[i]/sum_raw)*100]
            websiteArray += [vs.site[i]]
        return simplejson.dumps({"ids":websiteIDArray.tolist(), "websites":websiteArray, "percentages":percentages})

    @cp.expose
    def getUserPath(self, website):
        subpagearray = []
        possibilities = []
        global pagearray
        print pagearray
        for i in pagearray:
            try:
                print i[0]
                if website==i[0]:
                    subpagearray += [i[1:]]
                    possibilities+= [i[1]]
            except IndexError:
                print "IndexError!"
                pass
        x = build_dict(possibilities)
        sorted_x = sorted(x.items(), key=operator.itemgetter(1), reverse=True)
        pagearray = subpagearray
        totalelements = len(pagearray)
        returnvaluelist = []
        weight = []
        for i in sorted_x:
            returnvaluelist += [i[0]]
            weight += [(i[1]/(totalelements*1.0))*100]
        print returnvaluelist, weight
        return simplejson.dumps({"returnvaluelist":returnvaluelist, "weight":weight})

        @cp.expose
        def swap(self):
            global pagearray
            global timearray
            global state
            if state == "Buyers":
                pagearray = np.load("allpagearray.npy")
                timearray = np.load("alltimearray.npy")
                state = "All"
            else:
                pagearray = np.load("buyerpagearray.npy")
                timearray = np.load("buyertimearray.npy")
                state = "Buyers"


def build_dict(a_list=None):
    if a_list is None:
        a_list = []
    site_dict = {}
    for site in a_list:
        try:
            site_dict[site] = site_dict[site] + 1
        except KeyError:
            site_dict[site] = 1
    return site_dict


if __name__ == "__main__":
    vs = pd.read_pickle('violet_sitemap.pkl')
    filez = np.load('freq_last_first.txt')
    freq = filez['vs_array']
    last = filez['lp_array']
    first = filez['fp_array']
    sorted_first = np.argsort(first)
    sorted_last = np.argsort(last)
    cp.config.update({'server.socket_host': '0.0.0.0', 'server.socket_port':80})
    cp.quickstart(Main())

问题是当我通过jQuery在javascript中调用/ getUserPath时,它返回404错误,说/ getUserPath不存在,这没有任何意义,因为一切都暴露出来了转到实际网址

www.serverurlhere.com/getUserPath?website = http://otherurlhere.com/

显示有效负载返回且有效负载有效且正确。 Javascript是100%正确的,因为我在工作之间和不是这个文件之间的唯一文件。为什么404会出现?这对我没有任何意义,因为我所做的就是为这个文件添加一个方法并且它破坏了(交换方法)。该网站显示,其他一切工作,但/ getUserPath部分刚刚破解。 cherrypy服务器中的方法数量是否有限制?对于樱桃而言,我非常无知,而且很可能是对樱桃的限制。我用Google搜索,无法找到这样的其他内容......我只是不明白这里会发生什么......

谢谢,

˚F

1 个答案:

答案 0 :(得分:0)

这个问题的答案是使用从javascript发送的查询字符串参数为方法签名设置相同的参数名称。 CherryPy关心参数名称和接收的参数。

来自对问题的评论。

  

我明白了!谢谢你的帮助!事实证明这是一个非常愚蠢的错误。一切都运行正常,但我将名称为“input”的变量传递给getUserPath的名称改为名称为“website”,当POST请求发生时,当它收到除了确切变量名之外的其他内容时,它会变成404。 / p>