コード例 #1
0
 def POST(self):
     web.header("Access-Control-Allow-Origin", "*")
     must_params = ('cl_id', )
     params = web.input(requestPage='0')
     if util.paramsok(must_params, params) == Status.__params_not_ok__:
         response = Response(status=Status.__params_not_ok__)
         return util.objtojson(response)
     requestPage = params['requestPage'].encode('utf-8')
     del params['requestPage']
     #根据班号查学号,根据学号查学生
     st_has_cl = Student_has_class_model(class_cl_id=params.cl_id)
     st_has_cl_result = Student_has_class_model.getByPage(page=requestPage,
                                                          **st_has_cl)
     if st_has_cl_result:
         final_result = list()
         for s in range(len(st_has_cl_result)):
             st_ = st_has_cl_result[s].get('student_st_id')
             st = Student_model(st_id=st_)
             st_result = Student_model.getByPage(page=requestPage, **st)
             final_result.append(st_result[0])
         response = Response(status=Status.__success__, body=final_result)
         return util.objtojson(response)
     else:
         response = Response(status=Status.__obj_null__)
         return util.objtojson(response)
コード例 #2
0
    def POST(self):

        web.header("Access-Control-Allow-Origin","*")
        must_params = ('cl_id',)
        mydata = web.input()
        if util.paramsok(must_params, mydata) == Status.__params_not_ok__:
            response = Response(status = Status.__params_not_ok__ ,message = "参数错误!")
            return  util.objtojson(response)
        params = Class_model(cl_id = mydata.cl_id)
        teacher = model.Teacher_model.getByArgs(tc_level='管理员')
        if str(mydata.deletepassword) != teacher[0].tc_password:
            response = util.Response(status=util.Status.__error__,message = "密码错误")
            return util.objtojson(response)
        try:
            with orm.db.transaction():
                db.delete('student_has_class', where="class_cl_id = $class_cl_id", vars={'class_cl_id': params.cl_id, })
                if db.delete('class', where="cl_id = $cl_id", vars={'cl_id': params.cl_id, }):
                    response = Response(status=Status.__success__, message="班级删除成功!")
                    return util.objtojson(response)
                else:
                    response = Response(status=Status.__error__, message="班级删除失败!")
                    return util.objtojson(response)
        except Exception as e:
            util.getFileRotatingLog().debug(e)
            response = Response(status=Status.__error__, message="班级删除失败!")
            return util.objtojson(response)
コード例 #3
0
    def POST(self):
        web.header("Access-Control-Allow-Origin","*")
        must_params = ('st_id','cl_id')
        params = web.input()
        if util.paramsok(must_params, params) == Status.__params_not_ok__:
            response = Response(status = Status.__params_not_ok__  )
            return  util.objtojson(response)
        class_result = db.query("SELECT * FROM  class WHERE cl_id= $cl_id", vars={'cl_id':params.cl_id})
#         cl_id = class_result. __getitem__(0).get('cl_id')
        try:
            r1 = db.delete('student_has_class', where='class_cl_id=$cl_id and student_st_id = $st_id', vars={'cl_id':params.cl_id,'st_id':params.st_id})
            r2 = db.delete('information',where = 'student_st_id=$st_id and class_cl_id = $cl_id',vars={'st_id':params.st_id,'cl_id':params.cl_id})
            r3 = db.delete('student', where='st_id=$st_id', vars={'st_id':params.st_id})
            
            if r1:
                if r3:
                    response = Response(status = Status.__success__,message = "该学生已完全删除!")
                    return  util.objtojson(response)
                response = Response(status = Status.__success__,message = "该学生已从该课程班删除!")
                return  util.objtojson(response)
            else:
                response = Response(status = Status.__success__,message = "该学生已从该课程班删除!")
                return  util.objtojson(response)
        except Exception as e:
                response = Response(status = Status.__system_exception__,message = "该学生存在于其他课程班,已从当前课程班删除!")
                return  util.objtojson(response)
コード例 #4
0
ファイル: views.py プロジェクト: zhaofei1988/demo
def callback():
    code = request.args.get('code')
    if not code:
        logger.error("缺少code参数")
        return jsonify(Response.error(400, "缺少code参数"))
    logger.info("【code】" + str(code))
    # 通过code请求到access_token
    token_url = urls.get_token_url(code)
    resp = Request.get(token_url, to_dict=False)
    print(resp)
    try:
        access_token = re.findall("access_token=(.*?)&expires_in", resp)[0]
        logger.info("【access_token】" + str(access_token))
    except IndexError:
        logger.error('获取access_token错误')
        return jsonify(Response.error(400, "获取access_token错误"))
    session['qq_access_token'] = access_token
    # 通过access_token得到openid
    openid_url = urls.get_openid_url(access_token)
    resp = Request.get(openid_url)
    print(resp)
    openid = resp.get('openid')
    logger.info("【openid】" + str(openid))
    session['openid'] = openid
    return redirect(url_for('get_user_info'))
コード例 #5
0
def staticFile(pathname, base=".") -> Response:
    base = os.path.abspath(base)
    path = os.path.join(base, pathname[1:])
    headers = {
        "Content-Type": "text/html",
    }

    if not path.startswith(
            base
    ):  # unsafe! if absolute path of the requested file does not start with base, then it is requesting something like /../../../../boot/vmlinuz
        return Response(403, body=b"<h1>403 Forbidden</h1>", headers=headers)

    if os.path.exists(path):
        if path.endswith(".html") or path.endswith(".htm"):
            response = Response(200, headers=headers)
            with open(os.path.join(".", path), "rb") as f:
                response.body.extend(f.read())
        else:
            response = Response(403,
                                body=b"<h1>403 Forbidden</h1>",
                                headers=headers)
    else:
        response = Response(404,
                            body=b"<h1>404 Not Found</h1>",
                            headers=headers)

    return response
コード例 #6
0
 def POST(self):
     web.header("Access-Control-Allow-Origin","*")
     must_params = ('st_id','cl_name')
     params = web.input()   
     if util.paramsok(must_params, params) == Status.__params_not_ok__:
         response = Response(status = Status.__params_not_ok__  )
         return  util.objtojson(response)
     class_result = db.query("SELECT * FROM  class WHERE cl_name= $cl_name", vars={'cl_name':(params.cl_name.encode('utf-8'))})
     if class_result:
          cl_id = class_result. __getitem__(0).get('cl_id')
          st_has_class_result = db.query("SELECT * FROM  student_has_class WHERE class_cl_id= $cl_id", vars={'cl_id':cl_id})
          if st_has_class_result:
              st = Student_model(st_id = params.st_id)
              st_result = Student_model.getByArgs(**st)
              if st_result == list():
                  response = Response(status = Status.__obj_null__ ,body = st_has_class_result)
                  return util.objtojson(response)
              response = Response(status = Status.__success__,body = st_result)
              return util.objtojson(response)
          else:
             response = Response(status = Status.__obj_null__ ,body = st_has_class_result)
             return util.objtojson(response)
              
     else:
          response = Response(status = Status.__obj_null__)
          return util.objtojson(response)
コード例 #7
0
    def POST(self):

        #修改为不需要管理员密码就能够删除
        web.header("Access-Control-Allow-Origin", "*")
        must_params = ('cl_id', )
        params = web.input()

        if util.paramsok(must_params, params) == Status.__params_not_ok__:
            response = Response(status=Status.__params_not_ok__,
                                message="参数错误!")
            return util.objtojson(response)
        params = Class_model(cl_id=params.cl_id)
        print "delete_class"
        with orm.db.transaction():
            db.delete('student_has_class',
                      where="class_cl_id = $class_cl_id",
                      vars={
                          'class_cl_id': params.cl_id,
                      })
            if db.delete('class',
                         where="cl_id = $cl_id",
                         vars={
                             'cl_id': params.cl_id,
                         }):
                response = Response(status=Status.__success__,
                                    message="班级删除成功!")
                return util.objtojson(response)
            else:
                response = Response(status=Status.__error__, message="班级删除失败!")
                return util.objtojson(response)
コード例 #8
0
 def POST(self):
     must_params = ('cl_name')
     params = web.input()
     if util.paramsok(must_params, params) == Status.__params_not_ok__:
             response =  util.Response(Status.__params_not_ok__)
             return util.objtojson(response)
     
     params = Class_model(**params)
     if params.update():
         response = Response(status = Status.__success__)
         return  util.objtojson(response)
     else:
         response = Response(status = Status.__error__ )
         return  util.objtojson(response)
コード例 #9
0
ファイル: views.py プロジェクト: zhaofei1988/demo
def get_user_info():
    """
    从session中得到用户的access_token和openid得到用户的基本信息
    :return:
    """
    if 'qq_access_token' in session:
        openid = session.get('openid')
        access_token = session.get('qq_access_token')
        logger.info("【openid】" + str(openid))
        logger.info("【access_token】" + str(access_token))
        user_info_url = urls.get_user_info_url(access_token, openid)
        resp = Request.get(user_info_url)
        return jsonify(Response.success(resp))
    return jsonify(Response.error(400, "获取用户信息失败"))
コード例 #10
0
def runOnce(sock: socket.socket) -> None:
    (connection, (host, port)) = sock.accept()
    header = bytearray()

    while not header.endswith(b"\r\n" * 2):
        chunk = connection.recv(1)
        header.extend(chunk)

    request = Request.fromBytes(header)  # parse request
    if "Content-Length" in request.headers:

        while len(request.body) < int(request.headers["Content-Length"]):
            chunk = connection.recv(4096)
            request.body.extend(chunk)

    else:  # if browser does not include a Content-Length header, then request has no body
        pass

        # while True:
        #     chunk: bytes = connection.recv(4096)
        #     if chunk:
        #         request.body.extend(chunk)
        #     else:
        #         break

    headers = {"Content-Type": "application/json"}
    if request.pathname != "/product":
        response = Response(404, body=b"404 Not Found")
    elif request.params == {}:
        response = Response(400, body=b"400 Bad Request")
    else:
        try:
            operands = list(map(float,
                                request.params.values()))  # this could fail
            result = reduce(lambda x, y: x * y, operands)
            body = {
                "operation": "product",
                "operands": operands,
                "result": result
            }
            response = Response(200,
                                headers=headers,
                                body=bytes(json.dumps(body, indent=4), "utf8"))
        except:
            response = Response(400, body=b"400 Bad Request")

    connection.sendall(bytes(response))
    connection.close()
    print("{} {} {}".format(request.method, request.url, response.statusCode))
コード例 #11
0
 def POST(self):
     web.header("Access-Control-Allow-Origin","*")
     must_params = ('st_id',)
     params = web.input()
     if util.paramsok(must_params, params) == Status.__params_not_ok__:
         response = Response(status = Status.__params_not_ok__  )
         return  util.objtojson(response)
     st_modify  = Student_model(**params)
     result = st_modify.update()
     if result:
         response = Response(status = Status.__success__)
         return util.objtojson(response)
     else:
         response = Response(status = Status.__error__)
         return util.objtojson(response)
コード例 #12
0
 def POST(self):
     web.header("Access-Control-Allow-Origin","*")
     must_params = ('cl_name',)
     params = web.input()
     if util.paramsok(must_params, params) == Status.__params_not_ok__:
         response = Response(status = Status.__params_not_ok__  )
         return  util.objtojson(response)
     params = Class_model(**params)
     try:
         params.insert()
         response = Response(status = Status.__success__)
         return  util.objtojson(response)
     except Exception as e:
         response = Response(status = Status.__error__,message = e)
         return  util.objtojson(response)
コード例 #13
0
def runForever(port):
    sock = socket.socket(
        family=socket.AF_INET, type=socket.SOCK_STREAM
    )  # according to <https://docs.python.org/3/library/socket.html#socket.AF_INET>
    sock.bind(("", port))
    sock.listen(5)

    while True:
        try:
            (connection, (host, port)) = sock.accept()
        except:
            print("Keyboard interrupt. Exitting.")
            sock.close()
            break

        header = bytearray()

        while not header.endswith(b"\r\n" * 2):  # read the header only
            chunk = connection.recv(1)
            header.extend(chunk)

        request = Request.fromBytes(header)  # parse request

        path = "." + request.pathname
        headers = {
            "Content-Type": "text/html",
        }
        if os.path.exists(path):
            if path.endswith(".html") or path.endswith(".htm"):
                response = Response(200, headers=headers)
                with open(os.path.join(".", path), "rb") as f:
                    response.body.extend(f.read())
            else:
                response = Response(403,
                                    body=b"<h1>403 Forbidden</h1>",
                                    headers=headers)
        else:
            response = Response(404,
                                body=b"<h1>404 Not Found</h1>",
                                headers=headers)

        connection.sendall(bytes(response))
        print("{} {} {}".format(request.method, request.pathname,
                                response.statusCode))
        connection.close()
コード例 #14
0
ファイル: test_dcim.py プロジェクト: nrmjba/pynetbox
class InterfaceTestCase(unittest.TestCase, GenericTest):
    name = 'interfaces'

    @patch('pynetbox.lib.query.requests.get',
           side_effect=[
               Response(fixture='dcim/{}.json'.format(name + '_1')),
               Response(fixture='dcim/{}.json'.format(name + '_2')),
           ])
    def test_get_all(self, mock):
        ret = getattr(nb, self.name).all()
        self.assertTrue(ret)
        self.assertTrue(isinstance(ret, list))
        self.assertTrue(isinstance(ret[0], self.ret))
        self.assertEqual(len(ret), 71)
        mock.assert_called_with(
            'http://localhost:8000/api/dcim/interfaces/?limit=221&offset=50'.
            format(self.name),
            headers=HEADERS)
コード例 #15
0
 def test_get(self):
     with patch('pynetbox.lib.query.requests.get',
                return_value=Response(fixture='{}/{}.json'.format(
                    self.app, self.name[:-1]))) as mock:
         ret = getattr(nb, self.name).get(1)
         self.assertTrue(ret)
         self.assertTrue(isinstance(ret, self.ret))
         mock.assert_called_with(
             'http://localhost:8000/api/{}/{}/1/'.format(
                 self.app, self.name.replace('_', '-')),
             headers=HEADERS)
コード例 #16
0
ファイル: test_dcim.py プロジェクト: nrmjba/pynetbox
class SiteTestCase(unittest.TestCase, GenericTest):
    name = 'sites'

    @patch('pynetbox.lib.query.requests.get',
           return_value=Response(fixture='dcim/site.json'))
    def test_modify(self, mock):
        '''Test modifying custom field.
        '''
        ret = getattr(nb, self.name).get(1)
        ret.custom_fields['test_custom'] = "Testing"
        ret_serialized = ret.serialize()
        self.assertTrue(ret_serialized)
        self.assertFalse(ret._compare())
        self.assertEqual(ret.custom_fields['test_custom'], 'Testing')

    @patch('pynetbox.lib.query.requests.post',
           return_value=Response(fixture='dcim/site.json'))
    def test_create(self, mock):
        data = {'name': 'TEST1', 'custom_fields': {'test_custom': 'Testing'}}
        ret = nb.sites.create(**data)
        self.assertTrue(ret)
コード例 #17
0
def bbs(sock: Server):
	body = sock.recv_body()
	log = Log(LOG_FILE_PATH)

	if body.action == Action.READ.value:
		log_messages = log.read_messages()
		messages = [remove_password(message) for message in log_messages]
		response = Response(
			state=State.SUCCESS.value,
			messages=messages
		)
		sock.send_response(response)

	elif body.action == Action.WRITE.value:
		message = body.message
		log_messages = log.read_messages()
		log_messages.append(message)
		log.write_messages(log_messages)

		response = Response(
			state=State.SUCCESS.value
		)
		sock.send_response(response)

	elif body.action == Action.DELETE.value:
		message = body.message
		log_messages = log.read_messages()
		messages = delete_message(log_messages, message)
		log.write_messages(messages)

		if len(log_messages) == len(messages):  # IDまたはPASSWORDが間違っている
			response = Response(
				state=State.FAILED.value
			)
			sock.send_response(response)
		else:
			response = Response(
				state=State.SUCCESS.value
			)
			sock.send_response(response)
コード例 #18
0
class PrefixTestCase(unittest.TestCase, GenericTest):
    name = 'prefixes'
    name_singular = 'prefix'
    ip_obj_fields = ['prefix']

    @patch('pynetbox.lib.query.requests.get',
           return_value=Response(fixture='ipam/prefix.json'))
    def test_modify(self, mock):
        ret = nb.prefixes.get(1)
        ret.prefix = '10.1.2.0/24'
        ret_serialized = ret.serialize()
        self.assertTrue(ret_serialized)
        self.assertFalse(ret._compare())
        self.assertEqual(ret_serialized['prefix'], '10.1.2.0/24')
        self.assertTrue(netaddr.IPNetwork(ret_serialized['prefix']))
コード例 #19
0
class IPAddressTestCase(unittest.TestCase, GenericTest):
    name = 'ip_addresses'
    name_singular = 'ip_address'
    ip_obj_fields = ['address']

    @patch('pynetbox.lib.query.requests.get',
           return_value=Response(fixture='ipam/ip_address.json'))
    def test_modify(self, mock):
        ret = nb.prefixes.get(1)
        ret.description = 'testing'
        ret_serialized = ret.serialize()
        self.assertTrue(ret_serialized)
        self.assertFalse(ret._compare())
        self.assertEqual(ret_serialized['address'], '10.0.255.1/32')
        self.assertEqual(ret_serialized['description'], 'testing')
        self.assertTrue(netaddr.IPNetwork(ret_serialized['address']))
コード例 #20
0
 def test_get(self):
     with patch(
             'pynetbox.lib.query.requests.get',
             return_value=Response(fixture='{}/{}.json'.format(
                 self.app, self.name_singular or self.name[:-1]))) as mock:
         ret = getattr(nb, self.name).get(1)
         self.assertTrue(ret)
         self.assertTrue(isinstance(ret, self.ret))
         self.assertTrue(isinstance(dict(ret), dict))
         self.assertTrue(isinstance(str(ret), str))
         mock.assert_called_with(
             'http://localhost:8000/api/{}/{}/1/'.format(
                 self.app, self.name.replace('_', '-')),
             headers=HEADERS)
         if self.ip_obj_fields:
             for field in self.ip_obj_fields:
                 self.assertTrue(
                     isinstance(getattr(ret, field), netaddr.IPNetwork))
                 self.assertTrue(netaddr.IPNetwork(dict(ret)[field]))
コード例 #21
0
def get(url, headers=None):
    """Naive GET, does not handle any error or redirect"""
    request = Request(url)  # Your client must include a "Host: " header
    ip = socket.gethostbyname(request.hostname)
    port = request.port
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, port))
    sock.send(bytes(request))

    # use Content-Length to decide when the response has been fully transferred
    header = bytearray()

    while not header.endswith(b"\r\n" * 2):
        chunk = sock.recv(1)
        header.extend(chunk)

    response = Response.fromBytes(header)  # construct response from header
    if "Content-Length" in response.headers:
        contentLength = int(response.headers["Content-Length"]
                            )  # get Content-Length field. If none, no body

        while len(
                response.body
        ) < contentLength:  # keep reading body until reaching Content-Length
            chunk = sock.recv(4096)
            response.body.extend(chunk)

    else:  # if there is no Content-Length field in header, then assume server would close the stream when finishing

        while True:  # keep reading until stream is closed
            chunk = sock.recv(4096)
            if chunk:  # stream has been closed
                response.body.extend(chunk)
            else:
                break

    sock.close()

    return response
コード例 #22
0
def hello(request):
    name = request.GET.get('name', ["Anonymous"])[0]
    return Response(200, "Hello %s" % name)
コード例 #23
0
def index(request):
    return Response(200, "It works!")
コード例 #24
0
ファイル: test_dcim.py プロジェクト: nrmjba/pynetbox
class DeviceTestCase(unittest.TestCase, GenericTest):
    name = 'devices'

    @patch('pynetbox.lib.query.requests.get',
           return_value=Response(fixture='dcim/device.json'))
    def test_get(self, mock):
        ret = getattr(nb, self.name).get(1)
        self.assertTrue(ret)
        self.assertTrue(isinstance(ret, self.ret))
        self.assertTrue(isinstance(ret.primary_ip, pynetbox.ipam.IpAddresses))
        self.assertTrue(isinstance(ret.primary_ip4, pynetbox.ipam.IpAddresses))
        mock.assert_called_with('http://*****:*****@patch('pynetbox.lib.query.requests.get',
           return_value=Response(fixture='dcim/devices.json'))
    def test_multi_filter(self, mock):
        ret = getattr(nb, self.name).filter(role=['test', 'test1'],
                                            site='TEST1')
        self.assertTrue(ret)
        self.assertTrue(isinstance(ret, list))
        self.assertTrue(isinstance(ret[0], self.ret))
        mock.assert_called_with(
            'http://*****:*****@patch('pynetbox.lib.query.requests.get',
           return_value=Response(fixture='dcim/device.json'))
    def test_modify(self, mock):
        ret = nb.devices.get(1)
        ret.serial = '123123123123'
        ret_serialized = ret.serialize()
        self.assertTrue(ret_serialized)
        self.assertFalse(ret._compare())
        self.assertEqual(ret_serialized['serial'], '123123123123')

    @patch('pynetbox.lib.query.requests.post',
           return_value=Response(fixture='dcim/device.json'))
    def test_create(self, mock):
        data = {
            'name': 'test-device',
            'site': 1,
            'device_type': 1,
            'device_role': 1,
        }
        ret = nb.devices.create(**data)
        self.assertTrue(ret)

    @patch('pynetbox.lib.query.requests.get',
           side_effect=[
               Response(fixture='dcim/device.json'),
               Response(fixture='dcim/rack.json'),
           ])
    def test_get_recurse(self, mock):
        '''Test that automatic recursion works, and that nested items
        are converted to Response() objects.
        '''
        ret = getattr(nb, self.name).get(1)
        self.assertTrue(ret)
        self.assertTrue(isinstance(ret, self.ret))
        self.assertTrue(isinstance(ret.rack.role, self.ret))
コード例 #25
0
def runForever(port):
    sock = socket.socket(
        family=socket.AF_INET, type=socket.SOCK_STREAM
    )  # according to <https://docs.python.org/3/library/socket.html#socket.AF_INET>
    sock.bind(("", port))
    sock.listen(5)
    readers = {
        sock: None,
    }

    while True:
        try:
            readables, *_ = select.select(readers, [], [])
        except:
            print("Keyboard interrupt. Exitting.")

            for v in readers.keys():  # clean up
                v.close()

            break

        for readable in readables:
            if readable is sock:  # new connection coming in
                (connection, (ip, port)) = sock.accept()
                readers[connection] = {
                    "state": "header",
                    "header": bytearray()
                }
            else:  # other clients
                if readers[readable][
                        "state"] == "header":  # in the state of reading header
                    chunk = readable.recv(1)
                    readers[readable]["header"].extend(chunk)
                    if readers[readable]["header"].endswith(
                            b"\r\n" * 2):  # request header fully transferred
                        try:
                            request = Request.fromBytes(
                                readers[readable]
                                ["header"])  # parse request header
                        except:  # fail to parse header
                            traceback.print_exc()
                            response = Response(
                                403,
                                body=b"HTTP request is invalid: <pre>" +
                                readers[readable]["header"] + b"</pre>")
                            readable.sendall(bytes(response))
                            readable.close()
                            print("{} {} {}".format(request.method,
                                                    request.pathname,
                                                    response.statusCode))
                            readers.pop(readable)
                            continue

                        if (
                                "Content-Length" in request.headers
                                and request.headers["Content-Length"] == 0
                        ) or "Content-Length" not in request.headers:  # if Content-Length: 0 or Content-Length not available, serve immediately
                            response = staticFile(
                                request.pathname)  # generate response
                            readable.sendall(bytes(response))  # serve response
                            readable.close()
                            print("{} {} {}".format(request.method,
                                                    request.pathname,
                                                    response.statusCode))
                            del readers[readable]
                        else:  # need to read the whole request body
                            readers[readable]["state"] = "body"
                            readers[readable]["request"] = request
                            readers[readable].pop("header")
                            continue
                    else:  # request header not fully transferred
                        continue  # keep reading in the next iteration
                else:  # in the state of reading body
                    chunk = readable.recv(4096)
                    request = readers[readable]["request"]
                    request.body.extend(chunk)
                    if len(request.body) >= int(
                            request.headers["Content-Length"]
                    ):  # there is a Content-Length, guaranteed, because we have served all requests that do not have one already
                        response = staticFile(request.pathname)
                        readable.sendall(bytes(response))
                        readable.close()
                        print("{} {} {}".format(request.method,
                                                request.pathname,
                                                response.statusCode))
                        readers.pop(readable)
                    else:
                        continue
コード例 #26
0
ファイル: views.py プロジェクト: antonsapyanov/uaprom
def index(request):
    return Response(200, str(randint(0, 100)))
コード例 #27
0
ファイル: message.py プロジェクト: Yeolar/tornado-robot
 def deserialize(message):
     return ResponseMessage(message[0], Response.deserialize(message[1]))
コード例 #28
0
ファイル: fetchdata_events.py プロジェクト: xumi1993/SFT
def main():
    lalo_label, dep_label, begintime, endtime, cata_label, mag_label, phase_begin, phase_end, istimeb, istimee, \
    network, station, location, channel, stalist, islist, path, isoutsta, isresp = opt()
    if (not islist) and (istimeb or istimee):
        print(
            "Cannot specify time range by phases when station info was specified in command line"
        )
        sys.exit(1)
    date_label = "start=" + begintime.strftime("%Y-%m-%dT%H:%M:%S") + \
                 "&end=" + endtime.strftime("%Y-%m-%dT%H:%M:%S") + "&"
    events = Events(lalo_label, dep_label, mag_label, cata_label, date_label,
                    "", False)
    events.download()
    evt_lst = events.out_events
    if evt_lst == []:
        print("No event in this date range")
        sys.exit(1)
    for evt in evt_lst:
        evt = evt.strip()
        origin_time = get_time(evt.decode().split('|')[1])
        evla = float(evt.decode().split('|')[2])
        evlo = float(evt.decode().split('|')[3])
        evdp = float(evt.decode().split('|')[4])
        evmagtp = evt.decode().split('|')[9]
        evmag = evt.decode().split('|')[10]
        if not isoutsta:
            outpath = join(
                path, "evt.%s.%s%s" %
                (origin_time.strftime("%Y%m%d"), evmagtp, evmag))
            if not exists(outpath):
                makedirs(outpath)
        if islist:
            for sta in stalist:
                sta = sta.strip()
                lstnet = "net=" + sta.split()[0] + "&"
                lststa = "sta=" + sta.split()[1] + "&"
                stainfo = Stations('', lstnet, lststa, '', '', date_label, '',
                                   False, '', '')
                stainfo.download()
                stla = stainfo.out_station[0].decode().strip().split('|')[2]
                stlo = stainfo.out_station[0].decode().strip().split('|')[3]
                if isoutsta:
                    outpath = join(path, sta.split()[0] + '.' + sta.split()[1])
                    if not exists(outpath):
                        makedirs(outpath)
                if istimeb:
                    evt_begin = origin_time + timedelta(seconds=phase_begin[0])
                else:
                    out_label = "noheader=true&mintimeonly=true&traveltimeonly=true&"
                    dist_label = 'evloc=[' + str(evla) + ',' + str(
                        evlo) + ']&staloc=[' + stla + ',' + stlo + ']'
                    phase_label = "phases=" + phase_begin[0] + "&"
                    beg_tt = Traveltime("model=iasp91&", phase_label,
                                        "evdepth=" + str(evdp) + "&",
                                        out_label, dist_label)
                    beg_tt.download()
                    ttime = float(beg_tt.phs.strip().split()[0])
                    evt_begin = origin_time + timedelta(
                        seconds=ttime) + timedelta(seconds=phase_begin[1])
                if istimee:
                    evt_end = origin_time + timedelta(seconds=phase_end[0])
                else:
                    out_label = "noheader=true&mintimeonly=true&traveltimeonly=true&"
                    dist_label = 'evloc=[' + str(evla) + ',' + str(
                        evlo) + ']&staloc=[' + stla + ',' + stlo + ']'
                    phase_label = "phases=" + phase_end[0] + "&"
                    end_tt = Traveltime("model=iasp91&", phase_label,
                                        "evdepth=" + str(evdp) + "&",
                                        out_label, dist_label)
                    end_tt.download()
                    ttime = float(end_tt.phs.strip().split()[0])
                    evt_end = origin_time + timedelta(
                        seconds=ttime) + timedelta(seconds=phase_end[1])
                if evt_begin > evt_end:
                    print("start-time great than end-time in event %s %s.%s" %
                          (origin_time.strftime("%Y%m%d"), lstnet, lststa))
                    continue
                Timeseries(
                    sta.split()[0],
                    sta.split()[1],
                    sta.split()[2],
                    sta.split()[3], evt_begin.strftime("%Y-%m-%dT%H:%M:%S"),
                    evt_end.strftime("%Y-%m-%dT%H:%M:%S")).download(outpath)
                if not isoutsta:
                    if isresp == 1:
                        Response(sta.split()[0],
                                 sta.split()[1],
                                 sta.split()[2],
                                 sta.split()[3], [evt_begin, evt_end],
                                 False).download(outpath)
                    elif isresp == 2:
                        Response(sta.split()[0],
                                 sta.split()[1],
                                 sta.split()[2],
                                 sta.split()[3], [evt_begin, evt_end],
                                 True).download(outpath)
                    else:
                        continue
        else:
            evt_begin = origin_time + timedelta(seconds=phase_begin[0])
            evt_end = origin_time + timedelta(seconds=phase_end[0])
            Timeseries(network, station, location, channel,
                       evt_begin.strftime("%Y-%m-%dT%H:%M:%S"),
                       evt_end.strftime("%Y-%m-%dT%H:%M:%S")).download(outpath)
            if isresp == 1:
                Response(network, station, location, channel,
                         [evt_begin, evt_end], False).download(outpath)
            elif isresp == 2:
                Response(network, station, location, channel,
                         [evt_begin, evt_end], True).download(outpath)
            else:
                continue

    if islist and isoutsta:
        for sta in stalist:
            outpath = join(path, sta.split()[0] + '.' + sta.split()[1])
            sta = sta.strip()
            if isresp == 1:
                Response(sta.split()[0],
                         sta.split()[1],
                         sta.split()[2],
                         sta.split()[3], [evt_begin, evt_end],
                         False).download(outpath)
            elif isresp == 2:
                Response(sta.split()[0],
                         sta.split()[1],
                         sta.split()[2],
                         sta.split()[3], [evt_begin, evt_end],
                         True).download(outpath)
            else:
                continue