Python web 模块,input() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用web.input()

项目:CommunityCellularManager    作者:facebookincubator    | 项目源码 | 文件源码
def POST(self):
        """TODO (matt): need to verify: this is used by the dashboard only?
                        and is insecured?
        """
        # Always send back these headers.
        headers = {
            'Content-type': 'text/plain'
        }
        data = web.input()
        needed_fields = ["text", "to", "sender", "msgid"]
        if all(i in data for i in needed_fields):
            # Make sure we haven't already seen this message.
            if self.msgid_db.seen(str(data.msgid)):
                return data.msgid
            to = str(data.to)
            from_ = str(data.sender)
            body = str(data.text)
            self.fs_ic.send_to_number(to, from_, body)
            self.bill(to, from_)
            return web.ok(None, headers)
        else:
            return web.badrequest(None, headers)
项目:CommunityCellularManager    作者:facebookincubator    | 项目源码 | 文件源码
def POST(self):
        """Handles POST requests."""
        data = web.input()
        needed_fields = ["to", "from_number", "from_name", "body",
                         "service_type"]
        if all(i in data for i in needed_fields):
            params = {
                "to": str(data.to),
                "from_num": str(data.from_number),
                "from_name": str(data.from_name),
                "body": str(data.body),
                "service_type": str(data.service_type)
            }
            t = threading.Thread(target=self.worker, kwargs=params)
            t.start()
            raise web.Accepted()
        else:
            raise web.NotFound()
项目:CommunityCellularManager    作者:facebookincubator    | 项目源码 | 文件源码
def GET(self, command):
        """Handles get requests for certain commands."""
        valid_get_commands = ('req_usage', 'req_log', 'add_credit', 'req_checkin')
        if command not in valid_get_commands:
            return web.NotFound()
        d = web.input()
        if 'jwt' not in d:
            return web.BadRequest()
        try:
            data = self.check_signed_params(d['jwt'])
        except ValueError as e:
            logger.error("Value error dispatching %s" % (command,))
            return web.BadRequest(str(e))
        except Exception as e:
            logger.error("Other error dispatching %s: %s" % (command, str(e)))
            raise
        if command == "req_usage":  # NOTE: deprecated 2014oct23
            return self.req_checkin()
        if command == "req_log":
            return self.req_log(data)
        elif command == "add_credit":
            return self.adjust_credits(data)
        elif command == "req_checkin":
            return self.req_checkin()
项目:CommunityCellularManager    作者:facebookincubator    | 项目源码 | 文件源码
def POST(self):
        data = web.input()
        needed_fields = ["from_name", "ip", "port", "ret_num"]
        if all(i in data for i in needed_fields):
            from_name = str(data.from_name)
            ip = str(data.ip)
            port = str(data.port)
            ret_num = str(data.ret_num)
            params = {
                "from_name": from_name,
                "ip": ip,
                "port": port,
                "ret_num": ret_num
            }
            t = threading.Thread(target=self.worker, kwargs=params)
            t.start()
            raise web.Accepted()
        else:
            raise web.NotFound()
项目:nupic-history-server    作者:htm-community    | 项目源码 | 文件源码
def GET(self, modelId, columnIndex):
    """
    Returns entire history of SP for given column
    """
    requestInput = web.input()
    states = requestInput["states"].split(',')

    if modelId in modelCache.keys():
      print "Fetching SP {} from memory...".format(modelId)
      sp = modelCache[modelId]["sp"]
    else:
      try:
        print "Fetching SP {} from disk...".format(modelId)
        sp = SpFacade(modelId, ioClient)
      except:
        print "Unknown model id: {}".format(modelId)
        return web.badrequest()

    history = nupicHistory.getColumnHistory(modelId, int(columnIndex), states)

    return json.dumps(history)
项目:jd-crawler    作者:qiaofei32    | 项目源码 | 文件源码
def GET(self, _):
        params = web.input()
        # web.debug(params)
        date_list = []
        price_list = []
        price_info_dict = {
            "date": "['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']",
            "price": "[7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]"
        }
        try:
            item_id = params.item_id.encode("utf8")
            if not item_id:
                return render.index(price_info_dict)
            result = cursor.execute("select * from item_price where item_id = '%s' ORDER BY date desc" %item_id)
            rows = cursor.fetchall()
            for row in rows:
                # print row
                id, item_id, date, price = row
                date_list.append(date,)
                price_list.append(price)
                price_info_dict["date"] = str(date_list)
            price_info_dict["price"] = str(price_list)
            return render.index(price_info_dict)
        except:
            return render.index(price_info_dict)
项目:Desert-Fireball-Maintainence-GUI    作者:CPedersen3245    | 项目源码 | 文件源码
def GET(self):
        """
        Formats the specified drives.

        Returns:
            A JSON object with the following variables::

                consoleFeedback (str): User feedback.

        Raises:
            web.InternalError
        """
        if LoginChecker.loggedIn():
            data = {}
            try:
                data['consoleFeedback'] = format_hdd(web.input().args)
                outJSON = json.dumps(data)
            except IOError as e:
                raise web.InternalError(e.message)
            except RuntimeError as e:
                raise web.InternalError(e.message)

            return outJSON
项目:Desert-Fireball-Maintainence-GUI    作者:CPedersen3245    | 项目源码 | 文件源码
def GET(self):
        """
        Changes the system's timezone.

        Returns:
            A JSON object with the following variables::

                consoleFeedback (str): User feedback.

        web.input fetches the timezone information from the user.
        """
        if LoginChecker.loggedIn():
            data = {}
            timezone = web.input().zone
            data['consoleFeedback'] = timezone_change(timezone)
            outJSON = json.dumps(data)

            return outJSON
项目:Desert-Fireball-Maintainence-GUI    作者:CPedersen3245    | 项目源码 | 文件源码
def GET(self):
        """
        Deletes the specified thumbnail from the camera's filesystem.

        Returns:
            (int): 0.

        Raises:
            web.InternalError

        web.input fetches the filepath to delete..
        """
        if LoginChecker.loggedIn():

            try:
                remove_thumbnail(web.input())
            except IOError as e:
                raise web.InternalError(e.message)

            return 0
项目:Desert-Fireball-Maintainence-GUI    作者:CPedersen3245    | 项目源码 | 文件源码
def GET(self):
        """
        Fetches the specified .NEF file for the user to download.

        Returns:
            outJSON (json): Format::

                {success : boolean}

        Raises:
            web.NotFound

        web.input fetches the filepath for download.
        """
        if LoginChecker.loggedIn():
            data = {}

            try:
                data['success'] = download_picture(web.input())
                outJSON = json.dumps(data)
            except IOError as e:
                raise web.NotFound(e.message)

            return outJSON
项目:webapi    作者:IntPassion    | 项目源码 | 文件源码
def PUT(self):
        citype_input = web.input()
        v_ct_fids = db.query("SELECT ct.name ,convert(ct.description,'utf8') description,ct.owner,ct.family_id,"
                             "convert(ct.displayname,'utf8') displayname,ct.change_log from t_ci_type ct "
                             "WHERE ct.endtime = $endtime and  ct.family_id = $fid",vars={'endtime':ENDTIME,'fid':citype_input.get('fid',None)})
        ci_as_dict = []
        for ci in v_ct_fids:
           ci_as_dict.append(ci)
        ci_type_json = json.dumps(ci_as_dict, indent = 4,ensure_ascii=False, separators = (',',':')).decode("GB2312")
        ci_type_djson = json.loads(ci_type_json,encoding="gb2312")
        v_ct_fid_num = len(ci_type_djson)
        if v_ct_fid_num == 0:
            return 2 #there are no relative records to modify in table T_CI_TYPE
        elif v_ct_fid_num > 1:
            return 3 #there are more than one records to modify in table T_CI_TYPE
        v_curtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
        n = db.update('t_ci_type', where='family_id = $fid and endtime = $endtime', vars={'fid':citype_input.get('fid'),'endtime':ENDTIME}, endtime=v_curtime)
        v_fid = fn_create_ci_type(citype_input.get('name',ci_type_djson[0]['NAME']), citype_input.get('description',ci_type_djson[0]['DESCRIPTION']), citype_input.get('owner',ci_type_djson[0]['OWNER']),
                                  citype_input.get('fid',ci_type_djson[0]['FAMILY_ID']), citype_input.get('change_log',ci_type_djson[0]['CHANGE_LOG']),citype_input.get('displayname',ci_type_djson[0]['DISPLAYNAME']))
        return v_fid
项目:webapi    作者:IntPassion    | 项目源码 | 文件源码
def POST(self):
        ci_input = web.input()
        #Besides some fields in t_ci_attribute, input parameters also include the "name" field in t_ci and t_ci_attribute_type  
        v_ct_fids = db.query('select distinct a.family_id ci_fid,b.family_id type_fid from t_ci a, t_ci_attribute_type b where a.family_id=$cifid and a.endtime=$endtime and b.family_id=$ciattrtypefid and b.endtime=$endtime and a.type_fid=b.ci_type_fid',vars={'endtime':ENDTIME,'cifid':ci_input.get('ci_fid',None),'ciattrtypefid':ci_input.get('ci_attrtype_fid',None)})
        json_en = demjson.encode(v_ct_fids)
        json_de = demjson.decode(json_en)
        v_ct_fid_num = len(json_de)
        if v_ct_fid_num == 0:
            return 2 #there is no relative family id in table T_CI and T_CI_ATTRIBUTE_TYPE
        elif v_ct_fid_num > 1:
            return 3 #there are more than one relative family ids in table T_CI and T_CI_ATTRIBUTE_TYPE
        v_ci_fid = json_de[0]['CI_FID']
        v_ciattp_fid = json_de[0]['TYPE_FID']

        #Users don't need to input the family_id . The afferent parameter for the function is null
        v_fid = fn_create_ciattr(ci_input.get('value',None), ci_input.get('description',None), v_ciattp_fid, v_ci_fid,
                      ci_input.get('owner',None), None, 'initialization')
        return v_fid
项目:webapi    作者:IntPassion    | 项目源码 | 文件源码
def PUT(self):
        ci_input = web.input()
        v_ct_fids = db.query("select distinct a.value, convert(a.description,'utf8') description, a.type_fid, a.ci_fid, a.owner, a.family_id, a.change_log from t_ci_attribute a where a.endtime = $endtime and a.family_id = $fid ",vars={'endtime':ENDTIME,'fid':ci_input.get('fid',None)})
        ci_as_dict = []
        for ci in v_ct_fids:
           ci_as_dict.append(ci)
        ci_type_json = json.dumps(ci_as_dict, indent = 4,ensure_ascii=False, separators = (',',':')).decode("GB2312")
        ci_type_djson = json.loads(ci_type_json,encoding="gb2312")
        v_ct_fid_num = len(ci_type_djson)

        if v_ct_fid_num == 0:
            return 2 #there are no records to modify in table T_CI_ATTRIBUTE
        elif v_ct_fid_num > 1:
            return 3 #there are more than one records to modify in table T_CI_ATTRIBUTE
        v_curtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
        n = db.update('t_ci_attribute', where='family_id = $fid and endtime = $endtime', vars={'fid':ci_input.get('fid'),'endtime':ENDTIME}, endtime=v_curtime)
        v_fid = fn_create_ciattr(ci_input.get('value',ci_type_djson[0]['VALUE']), ci_input.get('description',ci_type_djson[0]['DESCRIPTION']), ci_type_djson[0]['TYPE_FID'], ci_type_djson[0]['CI_FID'],
                      ci_input.get('owner',ci_type_djson[0]['OWNER']), ci_type_djson[0]['FAMILY_ID'], ci_input.get('change_log',ci_type_djson[0]['CHANGE_LOG']))
        return v_fid
项目:webapi    作者:IntPassion    | 项目源码 | 文件源码
def POST(self):
        citype_input = web.input()
        #Besides some fields in t_ci_attribute_type, input parameters also include the "name" field in t_ci_type
        v_ct_fids = db.query('SELECT distinct ct.family_id FROM t_ci_type ct WHERE ct.endtime = $endtime and ct.family_id = $ctfid',vars={'endtime':ENDTIME,'ctfid':citype_input.get('ci_type_fid',None)})
        json_en = demjson.encode(v_ct_fids)
        json_de = demjson.decode(json_en)
        v_ct_fid_num = len(json_de)
        if v_ct_fid_num == 0:
            return 2 #there is no relative family_id in table T_CI_TYPE
        elif v_ct_fid_num > 1:
            return 3 #there are more than one relative family_ids in table T_CI_TYPE
        v_ct_fid = json_de[0]['FAMILY_ID']

        #Users don't need to input the family_id . The afferent parameter for the function is null
        v_fid = fn_create_ci_attrtype(citype_input.get('name',None), citype_input.get('description',None), v_ct_fid,
                                      citype_input.get('mandatory',None),
                      citype_input.get('owner',None), None, 'initialization', citype_input.get('displayname',None),
                                      citype_input.get('value_type',None))

        return v_fid
项目:webapi    作者:IntPassion    | 项目源码 | 文件源码
def PUT(self):
        citype_input = web.input()
        v_ct_fids = db.query("select a.name ,convert(a.description,'utf8') description,a.ci_type_fid,a.mandatory, a.owner,a.family_id,convert(a.displayname,'utf8') displayname,a.value_type, a.change_log from t_ci_attribute_type a where a.endtime = $aendtime and a.family_id = $fid ",vars={'aendtime':ENDTIME,'fid':citype_input.get('fid',None)})
        ci_as_dict = []
        for ci in v_ct_fids:
           ci_as_dict.append(ci)
        ci_type_json = json.dumps(ci_as_dict, indent = 4,ensure_ascii=False, separators = (',',':')).decode("GB2312")
        ci_type_djson = json.loads(ci_type_json,encoding="gb2312")
        v_ct_fid_num = len(ci_type_djson)
        if v_ct_fid_num == 0:
            return 2 #There are no records to modify in table t_ci_attribute_type
        elif v_ct_fid_num > 1:
            return 3 #There are more than one records to modify in table t_ci_attribute_type
        v_curtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
        n = db.update('t_ci_attribute_type', where='family_id = $fid and endtime = $endtime', vars={'fid':citype_input.get('fid'),'endtime':ENDTIME}, endtime=v_curtime)
        v_fid = fn_create_ci_attrtype(citype_input.get('name',ci_type_djson[0]['NAME']), citype_input.get('description',ci_type_djson[0]['DESCRIPTION']), 
                                      ci_type_djson[0]['CI_TYPE_FID'],citype_input.get('mandatory',ci_type_djson[0]['MANDATORY']),citype_input.get('owner',ci_type_djson[0]['OWNER']),
                                  ci_type_djson[0]['FAMILY_ID'], citype_input.get('change_log',ci_type_djson[0]['CHANGE_LOG']),citype_input.get('displayname',ci_type_djson[0]['DISPLAYNAME']),citype_input.get('value_type',ci_type_djson[0]['VALUE_TYPE']))        
        return v_fid
项目:webapi    作者:IntPassion    | 项目源码 | 文件源码
def POST(self):
        ci_input = web.input()
        #Besides some fields in t_ci, input parameters also include the "name" field in t_ci_type 
        v_ct_fids = db.query('SELECT distinct ct.family_id FROM t_ci_type ct WHERE ct.endtime = $endtime and ct.family_id = $ctfid',vars={'endtime':ENDTIME,'ctfid':ci_input.get('ci_type_fid',None)})
        json_en = demjson.encode(v_ct_fids)
        json_de = demjson.decode(json_en)
        v_ct_fid_num = len(json_de)
        if v_ct_fid_num == 0:
            return 2 #there is no relative family id in table T_CI_TYPE
        elif v_ct_fid_num > 1:
            return 3 #there are more than one relative family ids in table T_CI_TYPE
        v_ct_fid = json_de[0]['FAMILY_ID']

        #Users don't need to input the family_id . The afferent parameter for the function is null
        v_fid = fn_create_ci(ci_input.get('name',None), ci_input.get('description',None), ci_input.get('tag',None), ci_input.get('priority',0),
                      ci_input.get('owner',None), v_ct_fid, None, 'initialization')
        return v_fid
项目:webapi    作者:IntPassion    | 项目源码 | 文件源码
def PUT(self):
        ci_input = web.input()
        v_ct_fids = db.query("SELECT c.name,convert(c.description,'utf8') description,c.tag,c.priority,c.owner,c.type_fid,c.family_id,c.change_log FROM t_ci c WHERE c.endtime = $endtime and c.family_id = $fid",vars={'endtime':ENDTIME,'fid':ci_input.get('fid',None)})
        ci_as_dict = []
        for ci in v_ct_fids:
           ci_as_dict.append(ci)
        ci_type_json = json.dumps(ci_as_dict, indent = 4,ensure_ascii=False, separators = (',',':')).decode("GB2312")
        ci_type_djson = json.loads(ci_type_json,encoding="gb2312")
        v_ct_fid_num = len(ci_type_djson)

        if v_ct_fid_num == 0:
            return 2 #there are no records to modify in table t_ci
        elif v_ct_fid_num > 1:
            return 3 #there are more than one records to modify in table t_ci
        v_curtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
        n = db.update('t_ci', where='family_id = $fid and endtime = $endtime', vars={'fid':ci_input.get('fid'),'endtime':ENDTIME}, endtime=v_curtime)
        v_fid = fn_create_ci(ci_input.get('name',ci_type_djson[0]['NAME']), ci_input.get('description',ci_type_djson[0]['DESCRIPTION']), ci_input.get('tag',ci_type_djson[0]['TAG']), ci_input.get('priority',ci_type_djson[0]['PRIORITY']),
                      ci_input.get('owner',ci_type_djson[0]['OWNER']), ci_type_djson[0]['TYPE_FID'], ci_type_djson[0]['FAMILY_ID'], ci_input.get('change_log',ci_type_djson[0]['CHANGE_LOG']))
        return v_fid
项目:webapi    作者:IntPassion    | 项目源码 | 文件源码
def POST(self):
        ci_input = web.input()
        #Besides some fields in t_ci_relation, input parameters also include the "name" field in t_ci and t_ci_relation_type
        v_ct_fids = db.query('select distinct a.family_id type_fid, b.family_id sfid, c.family_id tfid from t_ci_relation_type a, t_ci b, t_ci c where a.relation = $relation and b.family_id = $source_fid and c.family_id = $target_fid and a.source_type_fid = b.type_fid and a.target_type_fid = c.type_fid and a.endtime=$endtime and b.endtime=$endtime and c.endtime=$endtime',vars={'endtime':ENDTIME,'relation':ci_input.get('relation',None),'source_fid':ci_input.get('source_fid',None),'target_fid':ci_input.get('target_fid',None)})
        json_en = demjson.encode(v_ct_fids)
        json_de = demjson.decode(json_en)
        v_ct_fid_num = len(json_de)
        if v_ct_fid_num == 0:
            return 2 #there is no relative family_id in table T_CI and T_CI_RELATION_TYPE
        elif v_ct_fid_num > 1:
            return 3 #there are more than one relative family_ids in table T_CI and T_CI_RELATION_TYPE
        v_sci_fid = json_de[0]['SFID']
        v_tci_fid = json_de[0]['TFID']
        v_cirela_fid = json_de[0]['TYPE_FID']


        v_fid = fn_create_cirela(v_sci_fid, v_tci_fid,v_cirela_fid,
                      ci_input.get('owner',None), None, 'initialization')
        return v_fid
项目:webapi    作者:IntPassion    | 项目源码 | 文件源码
def PUT(self):
        ci_input = web.input()
        v_ct_fids = db.query("select distinct t.source_fid, t.target_fid, t.type_fid,t.owner,t.family_id,t.change_log from t_ci_relation t where t.family_id=$fid and t.endtime=$endtime",vars={'endtime':ENDTIME,'fid':ci_input.get('fid',None)})
        ci_as_dict = []
        for ci in v_ct_fids:
           ci_as_dict.append(ci)
        ci_type_json = json.dumps(ci_as_dict, indent = 4,ensure_ascii=False, separators = (',',':')).decode("GB2312")
        ci_type_djson = json.loads(ci_type_json,encoding="gb2312")
        v_ct_fid_num = len(ci_type_djson)

        if v_ct_fid_num == 0:
            return 2 #there is no records to modify in table T_CI_RELATION
        elif v_ct_fid_num > 1:
            return 3 #there are more than one records to modify in table T_CI_RELATION
        v_curtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
        n = db.update('t_ci_relation', where='family_id = $fid and endtime = $endtime', vars={'fid':ci_input.get('fid'),'endtime':ENDTIME}, endtime=v_curtime)
        v_fid = fn_create_cirela(ci_type_djson[0]['SOURCE_FID'],ci_type_djson[0]['TARGET_FID'], ci_type_djson[0]['TYPE_FID'], 
                      ci_input.get('owner',ci_type_djson[0]['OWNER']), ci_type_djson[0]['FAMILY_ID'], ci_input.get('change_log',ci_type_djson[0]['CHANGE_LOG']))

        return v_fid
项目:webapi    作者:IntPassion    | 项目源码 | 文件源码
def POST(self):
        citype_input = web.input()
        #Besides some fields in t_ci_relation_type, input parameters also include the "name" field in t_ci_type . One for source, and the other one for target
        v_ct_fids = db.query('SELECT distinct ct.family_id sfid, tct.family_id tfid FROM t_ci_type ct, t_ci_type tct WHERE ct.endtime = $endtime and ct.family_id = $ctsfid and tct.endtime = $endtime and tct.family_id = $cttfid',vars={'endtime':ENDTIME,'ctsfid':citype_input.get('source_citype_fid',None),'cttfid':citype_input.get('target_citype_fid',None)})
        json_en = demjson.encode(v_ct_fids)
        json_de = demjson.decode(json_en)
        v_ct_fid_num = len(json_de)
        if v_ct_fid_num == 0:
            return 2 #there is no relative family id in table T_CI_TYPE
        elif v_ct_fid_num > 1:
            return 3 #there are more than one relative family ids in table T_CI_TYPE
        v_ct_sfid = json_de[0]['SFID']
        v_ct_tfid = json_de[0]['TFID']

        #Users don't need to input the family_id . The afferent parameter for the function is null
        v_fid = fn_create_ci_relatype(citype_input.get('name',None), v_ct_sfid, v_ct_tfid, 
                      citype_input.get('owner',None), citype_input.get('relation',None), None, 'initialization', citype_input.get('displayname',None))

        return v_fid
项目:webapi    作者:IntPassion    | 项目源码 | 文件源码
def PUT(self):
        citype_input = web.input()
        v_ct_fids = db.query("select t.name,convert(t.displayname,'utf8') displayname, t.source_type_fid,t.target_type_fid,t.owner,t.relation,t.family_id,t.change_log from t_ci_relation_type t where t.family_id=$fid and t.endtime=$endtime",vars={'endtime':ENDTIME,'fid':citype_input.get('fid',None)})
        ci_as_dict = []
        for ci in v_ct_fids:
           ci_as_dict.append(ci)
        ci_type_json = json.dumps(ci_as_dict, indent = 4,ensure_ascii=False, separators = (',',':')).decode("GB2312")
        ci_type_djson = json.loads(ci_type_json,encoding="gb2312")
        v_ct_fid_num = len(ci_type_djson)
        if v_ct_fid_num == 0:
            return 2 #there are no records to modify in table t_ci_relation_type
        elif v_ct_fid_num > 1:
            return 3 #there are more than one records to modify in table t_ci_relation_type
        v_curtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
        n = db.update('t_ci_relation_type', where='family_id = $fid and endtime = $endtime', vars={'fid':citype_input.get('fid'),'endtime':ENDTIME}, endtime=v_curtime)
        v_fid = fn_create_ci_relatype(citype_input.get('name',ci_type_djson[0]['NAME']), ci_type_djson[0]['SOURCE_TYPE_FID'], ci_type_djson[0]['TARGET_TYPE_FID'], 
                                      citype_input.get('owner',ci_type_djson[0]['OWNER']),citype_input.get('relation',ci_type_djson[0]['RELATION']),
                                  ci_type_djson[0]['FAMILY_ID'], citype_input.get('change_log',ci_type_djson[0]['CHANGE_LOG']),citype_input.get('displayname',ci_type_djson[0]['DISPLAYNAME']))        
        return v_fid
项目:WIFIHTTPMonitor    作者:kbdancer    | 项目源码 | 文件源码
def POST(self):
        key = web.input().get("key")
        ssid = web.input().get("ssid")
        inet = web.input().get("inet")
        ap = web.input().get("ap")
        channel = '6'

        # set iptables
        iptables(inet)
        # start monitor
        mon_iface = start_monitor(ap,channel)
        # start ap
        start_ap(mon_iface, channel, ssid, key, ap)
        # dhcpconf
        ipprefix = getIpfix(inet)
        dhcpconf = dhcp_conf(ipprefix)
        dhcp(dhcpconf, ipprefix)
        proc = subprocess.Popen(['python', sys.path[0] + '/sniffer.py'], stdout=DN, stderr=DN)
        return json.dumps({"code": 0})
项目:smartthings-monitor    作者:CNG    | 项目源码 | 文件源码
def GET(self):
        log.debug('connect.GET')
        user = current_user()
        if user:
            log.debug('user is {0}'.format(user))
            st = smartthings.SmartThings()
            params = web.input()
            log.debug('params is {0}'.format(params))
            if 'code' in params:
                # We just logged into SmartThings and got an OAuth code.
                user['token'] = st.token(params)
                user[SHORT_KEY] = new_shortcode(
                    collection=users.collection,
                    keyname=SHORT_KEY,
                    )
                users.register(**user) #  not totally sure why need **
                result_url = '/data/{0}'.format(user[SHORT_KEY])
                raise web.seeother(result_url)
            else:
                # We are about to redirect to SmartThings to authorize.
                raise web.seeother(st.auth_url())
        else:
            log.error('/connect was accessed without a user session.')
            raise web.seeother('/error')
项目:smartthings-monitor    作者:CNG    | 项目源码 | 文件源码
def POST(self):
        log.debug('data.POST')
        params = web.input()
        if "save" in params:
      pass
        elif "update" in params:
          pass
    else:
      pass


        user = current_user()
        if user:
            log.debug('user is {0}'.format(user))
            result_url = '/data/{0}'.format(user[SHORT_KEY])
            raise web.seeother(result_url)
        else:
            log.error('/data was POSTed to without a user session.')
            raise web.seeother('/error')
项目:py-script    作者:xiaoxiamin    | 项目源码 | 文件源码
def GET(self):
            print """
<script type="text/javascript">
function callback(item) {
  document.getElementById('content').innerHTML += "<p>" + item + "</p>";
}
</script>

<h2>Today's News</h2>

<div id="content"></div>

<h2>Contribute</h2>
<form method="post" action="/send">
  <textarea name="text"></textarea>
  <input type="submit" value="send" />
</form>
<iframe id="foo" height="0" width="0" style="display: none" src="/js"/></iframe>
            """
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def GET( self ):
        params = web.input( token = None, email = None )

        if params.token is None or params.email is None:
            return renderAlone.error( 'Missing parameter email or token.' )

        info = identmanager.request( 'confirm_email', { 'email' : params.email, 'token' : params.token } )

        if not info.isSuccess:
            return renderAlone.error( 'Error confirming email: %s' % info )

        if info.data[ 'confirmed' ]  is False:
            session.notice = 'Email already confirmed or bad, login as usual.'
            redirectTo( 'login' )

        session.notice = 'Email confirmed, you can now login.'

        redirectTo( 'login', no2fa = 'true' )
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def doGET( self ):
        params = web.input()

        info = model.request( 'get_backend_config', { 'oid' : session.orgs } )
        if not info.isSuccess:
            return renderAlone.error( 'Error getting backend configs: %s' % info )

        installers = info.data[ 'hcp_installers' ]
        profiles = info.data[ 'hbs_profiles' ]
        whitelist = info.data[ 'hcp_whitelist' ]

        info = audit.request( 'get_log', { 'oid' : session.orgs, 'limit' : 20 } )
        if not info.isSuccess:
            return renderAlone.error( 'Error getting audit logs: %s' % info )

        logs = info.data[ 'logs' ]

        return render.manage( installers, profiles, getOrgNames(), logs, whitelist )
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def doGET( self ):
        params = web.input( sensor_id = None )

        if params.sensor_id is None:
            raise web.HTTPError( '400 Bad Request: sensor id required' )

        info = model.request( 'get_sensor_info', { 'id_or_host' : params.sensor_id } )

        if not isOrgAllowed( AgentId( info.data[ 'id' ] ).org_id ):
            raise web.HTTPError( '401 Unauthorized' )

        info = model.request( 'get_lastips', { 'id' : params.sensor_id } )

        if not info.isSuccess:
            raise web.HTTPError( '503 Service Unavailable: %s' % str( info ) )

        return info.data
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def doGET( self ):
        params = web.input( sensor_id = None )

        if params.sensor_id is None:
            raise web.HTTPError( '400 Bad Request: sensor id required' )

        info = model.request( 'get_sensor_info', { 'id_or_host' : params.sensor_id } )

        if not isOrgAllowed( AgentId( info.data[ 'id' ] ).org_id ):
            raise web.HTTPError( '401 Unauthorized' )

        info = model.request( 'get_lastevents', { 'id' : params.sensor_id } )

        if not info.isSuccess:
            raise web.HTTPError( '503 Service Unavailable: %s' % str( info ) )

        return info.data
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def doGET( self ):
        params = web.input( sid = None )

        if params.sid is None:
            return renderAlone.error( 'Must provide a sid.' )

        info = model.request( 'get_sensor_info', { 'id_or_host' : params.sid } )
        aid = AgentId( info.data[ 'id' ] )
        hostname = info.data[ 'hostname' ]
        if not isOrgAllowed( aid.org_id ):
            return renderAlone.error( 'Unauthorized.' )

        cards = []
        orgNames = getOrgNames()
        tags = []
        resp = tagging.request( 'get_tags', { 'sid' : aid.sensor_id } )
        if resp.isSuccess:
            tags = resp.data.get( 'tags', {} ).values()[ 0 ].keys()
        cards.append( card_sensor_ident( aid, hostname, orgNames[ str( aid.org_id ) ], tags ) )
        cards.append( card_sensor_last( aid, hostname ) )
        cards.append( card_sensor_changes( aid, hostname ) )
        cards.append( card_sensor_bandwidth( aid, hostname ) )
        cards.append( card_sensor_traffic( aid, hostname, None, None ) )
        return render.sensor( hostname, aid, cards )
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def doGET( self ):
        params = web.input( atid = None )

        atid = params.atid

        try:
            atid = uuid.UUID( atid )
        except:
            atid = None

        if atid is None:
            return renderAlone.error( 'Must provide a valid atid.' )

        cards = []
        cards.append( card_event_explorer( atid ) )
        return render.explore( cards )
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def doGET( self ):
        params = web.input( eid = None, summarized = 1024 )

        if params.eid is None:
            return renderAlone.error( 'need to supply an event eid' )

        info = model.request( 'get_event', { 'id' : params.eid, 'with_routing' : True } )

        if not info.isSuccess:
            return renderAlone.error( str( info ) )

        event = info.data.get( 'event', [ None, ( {}, {} ) ] )
        eid, event = event
        routing, event = event

        if not isOrgAllowed( AgentId( routing[ 'aid' ] ).org_id ):
            return renderAlone.error( 'Unauthorized.' )

        thisAtom = event.values()[ 0 ].get( 'hbs.THIS_ATOM', None )

        cards = []
        cards.append( card_event( ( eid, sanitizeJson( event, summarized = params.summarized ) ), thisAtom ) )

        return render.event( cards )
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def doGET( self ):
        params = web.input( sid = None, after = None, before = None )

        if params.sid is None:
            return renderAlone.error( 'Must provide a sid.' )

        if params.after is None or params.after == '':
            params.after = time.time() - ( 60 * 10 * 1 )
        params.after = int( params.after )

        if params.before is None or params.before == '':
            params.before = time.time() + ( 60 * 60 * 1 )
        params.before = int( params.before )

        info = model.request( 'get_sensor_info', { 'id_or_host' : params.sid } )
        aid = AgentId( info.data[ 'id' ] )
        hostname = info.data[ 'hostname' ]
        if not isOrgAllowed( aid.org_id ):
            return renderAlone.error( 'Unauthorized.' )

        card = renderAlone.card_blink( aid.sensor_id, hostname, params.after, params.before )

        return render.blink( hostname, card )
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def doGET( self ):
        params = web.input( sensor_id = None )

        if params.sensor_id is None:
            raise web.HTTPError( '400 Bad Request: sensor id required' )

        info = model.request( 'get_sensor_info', { 'id_or_host' : params.sensor_id } )

        if not isOrgAllowed( AgentId( info.data[ 'id' ] ).org_id ):
            raise web.HTTPError( '401 Unauthorized' )

        usage = model.request( 'get_sensor_bandwidth', { 'sid' : params.sensor_id } )
        if not usage.isSuccess:
            raise web.HTTPError( '503 Service Unavailable: %s' % str( usage ) )

        return usage.data
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def doGET( self ):
        params = web.input( oid = None )

        if params.oid is None:
            return renderAlone.error( 'need to supply an oid' )

        instances = model.request( 'get_obj_instances', { 'oid' : params.oid, 'orgs' : session.orgs } )

        if instances.isSuccess and 0 != len( instances.data ) and 0 != len( instances.data[ 'instances' ] ):
            hostnames = getHostnames( [ x[ 1 ] for x in instances.data[ 'instances' ] ] )
            return render.obj_instance( instances.data[ 'instances' ], hostnames )
        elif not instances.isSuccess:
            session.notice = 'Error fetching instances: %s' % str( instances )
        else:
            session.notice = 'No instances found.'

        redirectTo( '' )
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def doPOST( self ):
        params = web.input( sid = None, tag = None )

        if params.sid is None:
            raise web.HTTPError( '400 Bad Request: sid required' )

        if params.tag is None:
            raise web.HTTPError( '400 Bad Request: tag required' )

        if not isSensorAllowed( params.sid ):
            raise web.HTTPError( '401 Unauthorized' )

        resp = tagging.request( 'del_tags', { 'sid' : AgentId( params.sid ).sensor_id, 
                                              'tag' : params.tag,
                                              'by' : session.email } )
        if resp.isSuccess:
            return { 'success' : True }
        else:
            raise web.HTTPError( '503 Service Unavailable: %s' % str( resp ) )
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def doPOST( self ):
        params = web.input( sid = None )

        try:
            sid = AgentId( params.sid ).sensor_id
        except:
            sid = None

        if sid is None:
            session.notice = 'Invalid sid to delete provided.'
            redirectTo( '' )

        if not isSensorAllowed( sid ):
            raise web.HTTPError( '401 Unauthorized' )

        resp = deployment.request( 'del_sensor', { 'sid' : sid } )
        if resp.isSuccess:
            session.notice = 'Sensor deleted.'
        else:
            session.notice = str( resp )
        redirectTo( 'sensors' )
项目:lantern-detection    作者:gongxijun    | 项目源码 | 文件源码
def GET(self):
            print """
<script type="text/javascript">
function callback(item) {
  document.getElementById('content').innerHTML += "<p>" + item + "</p>";
}
</script>

<h2>Today's News</h2>

<div id="content"></div>

<h2>Contribute</h2>
<form method="post" action="/send">
  <textarea name="text"></textarea>
  <input type="submit" value="send" />
</form>
<iframe id="foo" height="0" width="0" style="display: none" src="/js"/></iframe>
            """
项目:Weixin-Backstage    作者:liyouvane    | 项目源码 | 文件源码
def GET(self):
        #??????
        data = web.input()
        signature=data.signature
        timestamp=data.timestamp
        nonce=data.nonce
        echostr=data.echostr
        #???token
        token="YourToken" #????????????????token
        #?????
        list=[token,timestamp,nonce]
        list.sort()
        sha1=hashlib.sha1()
        map(sha1.update,list)
        hashcode=sha1.hexdigest()
        #sha1????        

        #??????????????echostr
        if hashcode == signature:
            return echostr
项目:MonopolyWeb    作者:zeal4u    | 项目源码 | 文件源码
def GET(self):
        # one ip can start one game at time
        ip = web.ctx.ip
        try:
            service = Game.manager.get_service_by_key(ip)
        except KeyError:

            # register game service
            Game.manager.register_service(ip)
            service = Game.manager.get_service_by_key(ip)

            # get players' names
            data = web.input()
            players_names = [data[str(x)] for x in range(len(data))]

            # init game service
            service.init_game(players_names)

        messages = [service.map_describe()]
        response = {
            'current_player': json.loads(json.dumps(service.current_player,cls=PlayerEncoder)),
            'messages': messages
        }
        web.header('Content-Type', 'application/json')
        return json.dumps(response)
项目:cosa-nostra    作者:joxeankoret    | 项目源码 | 文件源码
def POST(self):
    if not 'user' in session or session.user is None:
        f = register_form()
        return render.login(f)

    i = web.input(id=None, description=None)
    cluster_id = i.id
    if cluster_id is None:
      return render.error("No cluster id specified.")

    if not cluster_id.isdigit():
      return render.error("Invalid number.")
    cluster_id = int(cluster_id)

    desc = i.description
    vars = {"id":cluster_id}

    db = open_db()
    db.update('clusters', vars=vars, where="id = $id", description=desc)

    raise web.seeother("/view_cluster?id=%d" % cluster_id)

#-----------------------------------------------------------------------
项目:cosa-nostra    作者:joxeankoret    | 项目源码 | 文件源码
def GET(self):
    if not 'user' in session or session.user is None:
      f = register_form()
      return render.login(f)

    i = web.input(id=None)
    if i.id is None or not i.id.isdigit():
      return render.error("No cluster id specified or invalid one.")

    db = open_db()
    where = "id = $id"
    sql_vars = {"id":int(i.id)}
    ret = db.select("clusters", what="graph", vars=sql_vars, where=where)
    rows = list(ret)
    if len(rows) == 0:
      return render.error("Invalid cluster id.")

    g_text = rows[0]["graph"]
    g = CGraph()
    g.fromDict(json.loads(g_text))
    json_graph = graph2json(g)
    return json_graph

#-----------------------------------------------------------------------
项目:wxpytest    作者:loveQt    | 项目源码 | 文件源码
def GET(self):
        #??????
        data = web.input()
        signature=data.signature
        timestamp=data.timestamp
        nonce=data.nonce
        echostr = data.echostr
        #???token
        token="wxpytest" #????????????????token
        #?????
        list=[token,timestamp,nonce]
        list.sort()
        sha1=hashlib.sha1()
        map(sha1.update,list)
        hashcode=sha1.hexdigest()
        #sha1????

        #??????????????echostr
        if hashcode == signature:
            return echostr
项目:optf2    作者:Lagg    | 项目源码 | 文件源码
def GET(self, uid):
        user = {}
        callback = web.input().get("jsonp")

        try:
            user = models.user(uid).load()
            # JS is bad at numbers
            user["id64"] = str(user["id64"])
        except: pass

        web.header("Content-Type", jsonMimeType)

        jsonobj = json.dumps(user)
        if not callback:
            return jsonobj
        else:
            return callback + '(' + jsonobj + ');'
项目:optf2    作者:Lagg    | 项目源码 | 文件源码
def GET(self, app, sid):
        try:
            user, pack = models.load_inventory(sid, scope = app)
            items = pack["items"].values()
            sorter = views.sorting(items)
            items = sorter.sort(web.input().get("sort", sorter.byTime))
            cap = config.ini.getint("rss", "inventory-max-items")

            if cap: items = items[:cap]

            web.header("Content-Type", "application/rss+xml")
            return _feed_renderer.inventory_feed(app, user, items)

        except (steam.user.ProfileError, steam.items.InventoryError, steam.api.HTTPError) as E:
            raise rssNotFound()
        except Exception as E:
            log.main.error(str(E))
            raise rssNotFound()
项目:vcontrol    作者:CyberReboot    | 项目源码 | 文件源码
def POST(self, machine):
        web.header('Access-Control-Allow-Origin', self.allow_origin)
        # TODO how does this work with swagger?
        x = web.input(myfile={})
        filedir = '/tmp/templates/'+machine # change this to the directory you want to store the file in.
        try:
            if not os.path.exists(filedir):
                os.makedirs(filedir)
            if 'myfile' in x: # to check if the file-object is created
                filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
                filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
                fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored
                fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
                fout.close() # closes the file, upload complete.
                # copy file to vent instance
                cmd = "docker-machine scp "+filedir+"/"+filename+" "+machine+":/var/lib/docker/data/templates/"
                output = subprocess.check_output(cmd, shell=True)
                # remove file from vcontrol-daemon
                output = subprocess.check_output("rm -f "+filedir+"/"+filename, shell=True)
                return "successfully deployed", filename, "to", str(machine)
        except Exception as e:
            return "failed to deploy to", str(machine), str(e)
        return "failed to deploy to", str(machine)
项目:vcontrol    作者:CyberReboot    | 项目源码 | 文件源码
def POST(self, machine):
        web.header('Access-Control-Allow-Origin', self.allow_origin)
        # TODO how does this work with swagger?
        x = web.input(myfile={})
        filedir = '/tmp/files/'+machine # change this to the directory you want to store the file in.
        try:
            if not os.path.exists(filedir):
                os.makedirs(filedir)
            if 'myfile' in x: # to check if the file-object is created
                filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
                filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
                fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored
                fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
                fout.close() # closes the file, upload complete.
                # copy file to vent instance
                cmd = "docker-machine scp "+filedir+"/"+filename+" "+machine+":/files/"
                output = subprocess.check_output(cmd, shell=True)
                # remove file from vcontrol-daemon
                output = subprocess.check_output("rm -f "+filedir+"/"+filename, shell=True)
                return "successfully uploaded", filename, "to", str(machine)
        except Exception as e:
            return "failed to upload to", str(machine), str(e)
        return "failed to upload to", str(machine)
项目:MorSchedule    作者:Pohrom    | 项目源码 | 文件源码
def GET(self):
        i = web.input(xh = None)
        if i.xh == None:
            return "Usage: /ics?xh="
        else:
            return get_ics(i.xh)
项目:Information_retrieva_Projectl-    作者:Google1234    | 项目源码 | 文件源码
def GET(self):
        data=web.input()
        if data:
            searchword=data.searchword
        else:
            searchword=''
        news_list=list()
        topic=list()
        if searchword:
            cut = jieba.cut_for_search(searchword)
            word_list = []
            for word in cut:
                if word not in punct and word not in Letters_and_numbers:
                    word_list.append(word.encode("utf-8"))
            topK=query.calculate(word_list,config.query_return_numbers)
            for k in topK:
                data = dict()
                title, content, url= id_index.get_data(k)
                data['id'] = k
                data['content'] = content.decode("utf-8")[:config.query_return_snipper_size]
                data['title']=title.decode("utf-8")
                data['url'] = url.decode("utf-8")
                news_list.append(data)
            del data,cut,word_list,word,topK,title,content,url
            #word2Vec??????
            word2vec.cal(searchword.encode('utf-8'))
            print word2vec.result.length
            if word2vec.result.length==0:#????????1
                pass
            else:
                for i in range(config.recommand_topic_numbers):
                    topic.append(word2vec.result.word[i].char)
        return render.index(searchword,news_list,topic)
项目:Information_retrieva_Projectl-    作者:Google1234    | 项目源码 | 文件源码
def GET(self):
        data=web.input()
        if data:
            ID=data.id
            news = dict()
            title, content, url=id_index.get_data(int(ID))
            news['content'] = content.decode("utf-8")
            news['title'] = title.decode("utf-8")
            news['url'] = url.decode("utf-8")
            recomand=[]
            #????
            cut = jieba.cut_for_search(content)
            word_list = []
            for word in cut:
                if word not in punct and word not in Letters_and_numbers:
                    # ????????????????????
                    if recommand.stopword.has_key(word.encode("utf-8")):
                        pass
                    else:
                        word_list.append(word.encode("utf-8"))
            topk= recommand.calculate(word_list, config.recommand_numbers, 10)
            for i in topk:#????
            #for i in recommand.dic[int(ID)]:#????
                if i !=int(ID):
                    title, content, url=id_index.get_data(i)
                    recomand.append([title.decode('utf-8'),content.decode('utf-8'),url.decode('utf-8')])
            news['recommand']=recomand
            del title,content,url,recomand
        else:
            ID=''
            news = dict()
            news['title'] = "No Such News"
            news['content'] = "Oh No!"
            news['url'] = "#"
            news['recommand']=[['','',''] for m in range(config.recommand_numbers)]
        return render.news(news)