def __common_resp_handle(data, error, status): """ common response handling: - add common response headers - serialize response @data must be json serializable @error will be serialized with str() """ def __response_wrap(data=None, error=None): """ wrap response data/errors as dict - this should always be used when returning data to allow easy return of list objects, assist in error case distinction, etc. """ return dict(data=data, error=error) if not error: error_str = None else: error_str = str(error) # convert any Exception objects to serializable form ret_data = __response_wrap(data, error_str) resp_payload = json.dumps(ret_data) resp = Response(resp_payload, mimetype='application/json', status=status) resp.headers['Access-Control-Allow-Origin'] = '*' # more response processing return resp
def redirect(location, code=302): """Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since headers. .. versionadded:: 0.6 The location can now be unicode strings that are encoded using the :func:`iri_to_uri` function. :param location: the location the response should redirect to. :param code: the redirect status code. """ assert code in (301, 302, 303, 305, 307), 'invalid code' from werkzeug.wrappers import BaseResponse display_location = location if isinstance(location, unicode): from werkzeug.urls import iri_to_uri location = iri_to_uri(location) response = BaseResponse( '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n' '<title>Redirecting...</title>\n' '<h1>Redirecting...</h1>\n' '<p>You should be redirected automatically to target URL: ' '<a href="%s">%s</a>. If not click the link.' % (location, display_location), code, mimetype='text/html') response.headers['Location'] = location return response
def pin_auth(self, request): """Authenticates with the pin.""" exhausted = False auth = False if self.is_trusted(request.environ): auth = True elif self._failed_pin_auth > 10: exhausted = True else: entered_pin = request.args.get('pin') if entered_pin.strip().replace('-', '') == \ self.pin.replace('-', ''): self._failed_pin_auth = 0 auth = True else: time.sleep(self._failed_pin_auth > 5 and 5.0 or 0.5) self._failed_pin_auth += 1 auth = False rv = Response(json.dumps({ 'auth': auth, 'exhausted': exhausted, }), mimetype='application/json') if auth: rv.set_cookie(self.pin_cookie_name, str(int(time.time())), httponly=True) return rv
def redirect(location, code = 302): from werkzeug.wrappers import BaseResponse display_location = location if isinstance(location, unicode): from werkzeug.urls import iri_to_uri location = iri_to_uri(location) response = BaseResponse('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>Redirecting...</title>\n<h1>Redirecting...</h1>\n<p>You should be redirected automatically to target URL: <a href="%s">%s</a>. If not click the link.' % (location, display_location), code, mimetype='text/html') response.headers['Location'] = location return response
def pin_auth(self, request): """Authenticates with the pin.""" exhausted = False auth = False trust = self.check_pin_trust(request.environ) # If the trust return value is `None` it means that the cookie is # set but the stored pin hash value is bad. This means that the # pin was changed. In this case we count a bad auth and unset the # cookie. This way it becomes harder to guess the cookie name # instead of the pin as we still count up failures. bad_cookie = False if trust is None: self._fail_pin_auth() bad_cookie = True # If we're trusted, we're authenticated. elif trust: auth = True # If we failed too many times, then we're locked out. elif self._failed_pin_auth > 10: exhausted = True # Otherwise go through pin based authentication else: entered_pin = request.args.get('pin') if entered_pin.strip().replace('-', '') == \ self.pin.replace('-', ''): self._failed_pin_auth = 0 auth = True else: self._fail_pin_auth() rv = Response(json.dumps({ 'auth': auth, 'exhausted': exhausted, }), mimetype='application/json') if auth: rv.set_cookie(self.pin_cookie_name, '%s|%s' % ( int(time.time()), hash_pin(self.pin) ), httponly=True) elif bad_cookie: rv.delete_cookie(self.pin_cookie_name) return rv
def add_refresh(response: Response, refresh_time: int) -> Response: """Add Refresh header to response.""" response.headers["refresh"] = refresh_time return response
def get_response(app: callable, environ: dict): return BaseResponse.from_app(app, environ)
def block_sniffing(response: WebResponse) -> WebResponse: """Block MIME sniffing.""" response.headers["X-Content-Type-Options"] = "nosniff" return response
def get_response(self): return BaseResponse(self.to_string(), mimetype='application/atom+xml')
def test_base_application_basics(): br = BaseRoute('/', lambda request: BaseResponse('lolporte')) ba = BaseApplication([br]) client = Client(ba, BaseResponse) res = client.get('/') yield eq_, res.data, 'lolporte'
def __init__( self, response=None, status=200, headers=None, mimetype=None, content_type=None ): if isinstance(response, Stream): response = response.render("html", encoding=None, doctype="html") BaseResponse.__init__(self, response, status, headers, mimetype, content_type)
def response_wrapper(*args): resp = BaseResponse(*args) if resp.status_code in [200, 201]: resp.parsed_data = json.loads(resp.data.decode('utf-8')) return resp
def get_response(self): """Return a response object for the feed.""" return BaseResponse(self.to_string(), mimetype="application/atom+xml")
def post(self): """ 快汇支付,充值回调 :return: """ if not EnvironEnum.is_local_evn(current_app.config['FLASK_ENV']): # 无论如何都记录一条log current_app.logger.info( 'kuaihui deposit callback, ip: %s, args: %s, data: %s', IpKit.get_remote_ip(), request.args, request.json) form, error = KhpayForm().request_validate() if error: current_app.logger.fatal('msg: %s, args: %s, data: %s', error.message, request.args, request.json) return BaseResponse(error.message) # 交易订单id tx_id = form.client_ordid.data # 充值通道 订单id channel_tx_id = form.ordid.data # 实际支付金额 tx_amount = Decimal(form.amount.data) # 订单状态: 成功/失败 status = form.status.data # 客户端IP client_ip = form.client_ip.data custid = form.custid.data kuai_hui_dict = { "PAY5f34c380-b8e6-11e9-9edc-511803f475f9": ThirdPayConfig.KUAIHUI.value, "PAY5f34c380-b8e6-11e9-9edc-511803f475f9": ThirdPayConfig.KUAIHUI_0bd0d8.value } # 签名验证 if not CallbackKhpay.check_sign(form, kuai_hui_dict[custid]): current_app.logger.fatal('invalid sign, client_ip: %s, data: %s', client_ip, request.json) return BaseResponse('FAIlURE') # IP白名单校验 if not CallbackKhpay.check_ip(client_ip): current_app.logger.fatal('ip not allow, client_ip: %s, data: %s', client_ip, request.json) return BaseResponse('FAIlURE') order = DepositTransactionCtl.get_order(tx_id) if not order: return BaseResponse('FAIlURE') if order.state.is_final_state: # 已经通知了就返回成功 return BaseResponse('{"status_code": 200}') if status == 'waiting': return BaseResponse('FAIlURE') if status == 'finish': # 支付成功 if not DepositTransactionCtl.success_order_process( order, tx_amount, channel_tx_id): return BaseResponse('FAIlURE') else: # 支付失败 if not DepositTransactionCtl.failed_order_process( order, tx_amount, channel_tx_id): return BaseResponse('FAIlURE') return BaseResponse('{"status_code": 200}')
def get_response(self, environ): headers = [('Content-Type', 'application/json')] return BaseResponse(self.get_body(environ), self.error, headers)
def get_json_response(response: BaseResponse) -> Dict: import json return json.loads(response.get_data(as_text=True))
def get(self): return BaseResponse('', 200)
def get_response(self, environ): environ = _get_environ(environ) from werkzeug.wrappers import BaseResponse headers = self.get_headers(environ) return BaseResponse(self.get_body(environ), self.code, headers)
def foo(environ, start_response): return BaseResponse('Test')
def post(self): """ 专一付代付回调 :return: """ if not EnvironEnum.is_local_evn(current_app.config['FLASK_ENV']): # 无论如何都记录一条log current_app.logger.info( 'zhuanyifu withdraw callback, ip: %s, data: %s, headers: %s', IpKit.get_remote_ip(), request.json, request.headers) event = request.headers.get('ChinaRailway-Event') signature = request.headers.get('ChinaRailway-Signature') form, error = ZhuanYeFuWithdrawForm().request_validate() if error: current_app.logger.fatal('msg: %s, data: %s', error.message, request.args) return BaseResponse('FAIlURE') pp = signature.split('.') if event != "Pay.Succeeded": return ResponseSuccess(code=500).as_response() # 交易ID tx_id = form.order.data fee = Decimal(form.fee.data) order = WithdrawTransactionCtl.get_order(tx_id) if not order: return ResponseSuccess( code=500, message='curr order no found').as_response() curr_status = order.state if curr_status != OrderStateEnum.DEALING: return ResponseSuccess( code=500, message='curr order status must be DEALING').as_response() print(order.channel_id, form.order.data, order.merchant, order.create_time, order.order_id, order.uid) channel_config = ProxyChannelConfig.query_by_channel_id( order.channel_id) channel_cost = FeeCalculator.calc_cost(order.amount, channel_config.fee_type, channel_config.fee) if fee != channel_cost: current_app.logger.error( "ZYF withdraw fee info order_id:{}, channel_fee: {}, channel_cost:{}" .format(order.order_id, fee, channel_cost)) try: flag = CryptoKit.rsa_verify( pp[1], pp[0], channel_config.channel_enum.conf['plat_public_key']) if flag != True: return ResponseSuccess(code=500, message='签名错误').as_response() except Exception as e: return ResponseSuccess(code=500).as_response() # 代付金额 tx_amount = Decimal(form.amount.data) # 代付费率 fee = Decimal(form.fee.data) # 通道订单号 transaction = form.transaction.data client_ip = form.client_ip.data status = form.status.data if str(status) == "1": """ 修改订单状态, 记录代付费率 """ if not WithdrawTransactionCtl.order_success(order, tx_amount): return ResponseSuccess(code=500).as_response() elif str(status) == "2": """ 代付订单失败, 1.给用户退款,给商户退款+手续费 2. 修改订单状态 """ # order = WithdrawTransactionCtl.get_order(merchant, order_id) if not WithdrawTransactionCtl.order_fail(order): return ResponseSuccess(code=500).as_response() return ResponseSuccess(code=204).as_response()
def post(self): if not EnvironEnum.is_local_evn(current_app.config['FLASK_ENV']): # 无论如何都记录一条log current_app.logger.info( 'zhuanyifu deposit callback, ip: %s, data: %s, headers: %s', IpKit.get_remote_ip(), request.json, request.headers) event = request.headers.get('ChinaRailway-Event') signature = request.headers.get('ChinaRailway-Signature') form, error = ZhuanYeFuWithdrawForm().request_validate() if error: current_app.logger.fatal('msg: %s, data: %s', error.message, request.args) return BaseResponse('FAIlURE') client_ip = form.client_ip.data tx_amount = Decimal(form.amount.data) fee = Decimal(form.fee.data) channel_tx_id = form.transaction.data # if not CallbackZYF.check_ip(client_ip): # current_app.logger.fatal('ip not allow, client_ip: %s, data: %s, body: %s', client_ip, request.args, # request.json) # return ResponseSuccess(code=500, message='ip not allow').as_response() pp = signature.split('.') if event != "Charge.Succeeded": return ResponseSuccess(code=500).as_response() order = DepositTransactionCtl.get_order(form.order.data) if not order: return ResponseSuccess( code=500, message='curr order no found').as_response() curr_status = order.state if curr_status != OrderStateEnum.INIT: return ResponseSuccess( code=500, message='curr order status must be DEALING').as_response() channel_config = ChannelConfig.query_by_channel_id(order.channel_id) # 检查通道手续费与系统计算出的手续费 channel_cost = FeeCalculator.calc_cost(order.amount, channel_config.fee_type, channel_config.fee) if Decimal(fee) != channel_cost: current_app.logger.error( "ZYF deposit fee info order_id:{}, channel_fee: {}, channel_cost:{}" .format(order.order_id, Decimal(fee), channel_cost)) flag = CallbackZYF.check_sign(pp=pp, channel_config=channel_config) if not flag: current_app.logger.fatal( 'invalid sign, client_ip: %s, data: %s, body: %s', client_ip, request.args, request.json) return ResponseSuccess(code=500, message='签名错误').as_response() status = form.status.data if str(status) == '1': if not DepositTransactionCtl.success_order_process( order, tx_amount, channel_tx_id, client_ip): return ResponseSuccess(code=500, message='订单状态更新失败').as_response() else: return ResponseSuccess(code=500, message='签名错误').as_response() elif str(status) == '2': if not DepositTransactionCtl.failed_order_process( order, tx_amount, channel_tx_id, client_ip): return ResponseSuccess(code=500, message='订单状态更新失败').as_response() elif str(status) == '0': pass return ResponseSuccess(code=204).as_response()
def post(self): """ RuKouMy,充值回调 :return: """ client_ip = IpKit.get_remote_ip() if not EnvironEnum.is_local_evn(current_app.config['FLASK_ENV']): # 无论如何都记录一条log current_app.logger.info( 'RuKouMy deposit callback, ip: %s, json: %s', IpKit.get_remote_ip(), request.json) if not CallbackRuKouMy.check_ip(client_ip): current_app.logger.error( 'ip not allow, client_ip: %s, data: %s, body: %s', client_ip, request.args, request.json) return BaseResponse('error') resp_body = request.json sign = resp_body.pop("sign") sorted_params = sorted(list(resp_body.keys())) resp_body['real_amount'] = "{:.2f}".format( int(resp_body['real_amount'])) resp_body['pay_amount'] = "{:.2f}".format(int(resp_body['pay_amount'])) sign_str = "&".join([ "{}={}".format(k, resp_body[k]) for k in sorted_params if resp_body.get(k, False) or k in ["code"] ]) flag = CallbackRuKouMy.check_sign(sign, sign_str) if not flag: current_app.logger.error( 'invalid sign, data: %s, sign: %s, data: %s', client_ip, sign, sign_str) return BaseResponse('error') order_id = resp_body['order_id'] order = DepositTransactionCtl.get_order(order_id) if not order: return BaseResponse('success') if order.state.name == OrderStateEnum.SUCCESS.name: return BaseResponse('success') tx_amount = Decimal(str(request.json['real_amount'])) channel_tx_id = request.json['order_no'] code = resp_body['code'] if code == 0: # 支付成功 if not DepositTransactionCtl.success_order_process( order, tx_amount, channel_tx_id): return BaseResponse('error') else: # 支付失败 if not DepositTransactionCtl.failed_order_process( order, tx_amount, channel_tx_id): return BaseResponse('error') return BaseResponse('success')
def __init__(self, description=None): super().__init__(description) resp = BaseResponse(response=self.to_json(), status=self.code, mimetype='application/json') self.response = resp
def __init__( self, response=None, status=200, headers=None, mimetype=None, content_type=None ): if isinstance(response, Stream): response = response.render("html", encoding=None, doctype="html") BaseResponse.__init__(self, response, status, headers, mimetype, content_type)
def __init__(self, response, status, headers): BaseResponse.__init__(self, response, status, headers) self.body_data = pickle.loads(self.response_body)
from __future__ import unicode_literals from nose.tools import raises, eq_, ok_ from werkzeug.test import Client from werkzeug.wrappers import BaseResponse from clastic import Application, render_basic from clastic.application import BaseApplication from clastic.route import BaseRoute, Route from clastic.route import (InvalidEndpoint, InvalidPattern, InvalidMethod) from clastic.route import S_STRICT, S_REWRITE, S_REDIRECT from clastic.errors import NotFound, ErrorHandler MODES = (S_STRICT, S_REWRITE, S_REDIRECT) NO_OP = lambda: BaseResponse() def test_new_base_route(): # note default slashing behavior rp = BaseRoute('/a/b/<t:int>/thing/<das+int>') d = rp.match_path('/a/b/1/thing/1/2/3/4') yield eq_, d, {u't': 1, u'das': [1, 2, 3, 4]} d = rp.match_path('/a/b/1/thing/hi/') yield eq_, d, None d = rp.match_path('/a/b/1/thing/') yield eq_, d, None rp = BaseRoute('/a/b/<t:int>/thing/<das*int>', methods=['GET'])
def get_handler(self, req): return BaseResponse(self.req_template.render( profileoptions=self.config.profileoptions), mimetype='text/html')