• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python util.RequestValidator类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twilio.util.RequestValidator的典型用法代码示例。如果您正苦于以下问题:Python RequestValidator类的具体用法?Python RequestValidator怎么用?Python RequestValidator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了RequestValidator类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: decorator

    def decorator(request, *args, **kwargs):
        # Here we'll use the twilio library's request validation code to ensure
        # that the current request actually came from twilio, and isn't a
        # forgery if settings.DEBUG is True. If it is a forgery, then we'll
        #return a HTTP 403 error (forbidden).
        if not settings.DEBUG:
            try:
                url = request.build_absolute_uri()
                signature = request.META['HTTP_X_TWILIO_SIGNATURE']
            except (AttributeError, KeyError):
                return HttpResponseForbidden()
    
            validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)
            if not validator.validate(url, request.POST, signature):
                return HttpResponseForbidden()
    
            # Run the wrapped view, and capture the data returned.
            response = require_POST(f(request, *args, **kwargs))
        else:
            response = f(request, *args, **kwargs)

        # If the view returns a string, we'll assume it is XML TwilML data and
        # pass it back with the appropriate mimetype. We won't check the XML
        # data because that would be too time consuming for every request.
        # Instead, we'll let the errors pass through to be dealt with by the
        # developer.
        if isinstance(response, Verb):
            return HttpResponse(response, mimetype='text/xml')
        else:
            return response
开发者ID:leetrout,项目名称:django-twilio,代码行数:30,代码来源:decorators.py


示例2: get

 def get(self):
     client = TwilioRestClient(account_sid, auth_token)
     validator = RequestValidator(auth_token)
     url = self.request.url
     params = {}
     try:
         twilio_signature = self.request.headers["X-Twilio-Signature"]
         logging.debug(twilio_signature)
     except:
         twilio_signature = ""
     if validator.validate(url, params, twilio_signature):
         logging.debug("Validated")
         call_id = self.request.get('to_call')
         print call_id
         infos = Call.query(Call.key==ndb.Key(Call, int(call_id))).fetch()
         print infos
         for info in infos:
             print info
             for i in json.loads(info.calls):
                 print i
                 call_out = client.calls.create(to=i, from_="2065576875",
                                                  url="https://teen-link.appspot.com/make-calls?RecordingUrl=" + self.request.get("RecordingUrl"),
                             method="GET",
                             if_machine="Continue")
                 print call_out
     else:
         self.response.headers['Content-Type'] = 'text/html'
         self.response.write("Please don't try to hack me.")
开发者ID:matthewbentley,项目名称:teenlink,代码行数:28,代码来源:callhandler.py


示例3: decorated

        def decorated(*args, **kwargs):

            print request.values

            if 'CallSid' not in request.values:
                return abort(401, 'Request must be a signed Twilio request.')

            if validate and False:

                validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)
                sig_header = request.headers.get('X-Twilio-Signature', '')

                if request.method == 'POST':
                    vparams = request.form
                    vurl = request.url
                else:
                    vparams = {}
                    vurl = request.url

                # validator params are called URL, POST vars, and signature
                if not validator.validate(vurl, vparams, sig_header):
                    return abort(401, 'Request signature could not be validated')

            # load the call from Mongo or create if one does not exist
            g.call = load_call(request.values['CallSid'], request.values)

            g.zipcode = read_context('zipcode', None)
            g.legislator = read_context('legislator', None)

            twilio_response = func(*args, **kwargs)

            return Response(str(twilio_response), mimetype='application/xml')
开发者ID:jcarbaugh,项目名称:calloncongress,代码行数:32,代码来源:decorators.py


示例4: validate

    def validate(self, request):
        validator = RequestValidator(self.auth[1])
        signature = request.META.get('HTTP_X_TWILIO_SIGNATURE', '')

        base_url = settings.TEMBA_HOST
        url = "https://%s%s" % (base_url, request.get_full_path())
        return validator.validate(url, request.POST, signature)
开发者ID:churcho,项目名称:rapidpro,代码行数:7,代码来源:clients.py


示例5: test_international_sms

    def test_international_sms(self):

        token = os.environ["TWILIO_AUTH_TOKEN"]
        validator = RequestValidator(token)

        uri = "http://www.postbin.org/1c2pdoc"
        params = {
            "AccountSid": "AC4bf2dafb92341f7caf8650403e422d23",
            "ApiVersion": "2010-04-01",
            "Body": "Chloéñ",
            "From": "+15305451766",
            "FromCity": "SOUTH LAKE TAHOE",
            "FromCountry": "US",
            "FromState": "CA",
            "FromZip": "89449",
            "SmsMessageSid": "SM51d6d055f53f1072543872c601aae89b",
            "SmsStatus": "SM51d6d055f53f1072543872c601aae89b",
            "SmsStatus": "received",
            "To": "+15304194304",
            "ToCity": "WOODLAND",
            "ToCountry": "US",
            "ToState": "CA",
            "ToZip": "95695",
            }

        expected = "UHkWu+6WLOzPunzb8PuCGPeW1Uw="

        self.assertEquals(validator.compute_signature(uri, params), expected)
        self.assertTrue(validator.validate(uri, params, expected))
开发者ID:MC6,项目名称:twilio-python,代码行数:29,代码来源:test_validation.py


示例6: hello

def hello():
    """Respond to incoming requests."""

    resp = twiml.Response()
    first_request = True
    twilio_account_sid = os.environ.get("TWILIO_ACCOUNT_SID")
    twilio_auth_token = os.environ.get("TWILIO_AUTH_TOKEN")
    twilio_number = os.environ.get("TWILIO_NUMBER")

    validator = RequestValidator(twilio_auth_token)
    
    if 'X-Twilio-Signature' not in request.headers:        
        if first_request:
            first_request = False
        else:
            abort(401)
    else:         
        my_url = request.url
        if my_url.startswith('http://'):
            my_url = my_url.replace("http", "https")
        
        params = request.form
        
        twilio_signature = request.headers['X-Twilio-Signature']
        
        if validator.validate(my_url, params, twilio_signature):
            resp.say("Hello! Welcome to the telephone fizz buzz game!")
            with resp.gather(timeout=10, finishOnKey="*", action="/handle-key", method="POST") as g:
                g.say("Please enter your number and then press star.")
        else: 
            abort(401)
            
    return str(resp)
开发者ID:wentaoxu415,项目名称:fizz_buzz,代码行数:33,代码来源:run.py


示例7: decorator

    def decorator(request, *args, **kwargs):

        # Only handle Twilio forgery protection stuff if we're running in
        # production. This way, developers can test their Twilio view code
        # without getting errors.
        if not settings.DEBUG:

            # Attempt to gather all required information to allow us to check the
            # incoming HTTP request for forgery. If any of this information is not
            # available, then we'll throw a HTTP 403 error (forbidden).
            #
            # The required fields to check for forged requests are:
            #
            #   1. ``TWILIO_ACCOUNT_SID`` (set in the site's settings module).
            #   2. ``TWILIO_AUTH_TOKEN`` (set in the site's settings module).
            #   3. The full URI of the request, eg: 'http://mysite.com/test/view/'.
            #      This may not necessarily be available if this view is being
            #      called via a unit testing library, or in certain localized
            #      environments.
            #   4. A special HTTP header, ``HTTP_X_TWILIO_SIGNATURE`` which
            #      contains a hash that we'll use to check for forged requests.
            # Ensure the request method is POST
            response = require_POST(f)(request, *args, **kwargs)
            if isinstance(response, HttpResponse):
                return response

            # Validate the request
            try:
                validator = RequestValidator(django_twilio_settings.TWILIO_AUTH_TOKEN)
                url = request.build_absolute_uri()
                signature = request.META['HTTP_X_TWILIO_SIGNATURE']
            except (AttributeError, KeyError):
                return HttpResponseForbidden()

            # Now that we have all the required information to perform forgery
            # checks, we'll actually do the forgery check.
            if not validator.validate(url, request.POST, signature):
                return HttpResponseForbidden()

        # If the user requesting service is blacklisted, reject their
        # request.
        blacklisted_resp = get_blacklisted_response(request)
        if blacklisted_resp:
            return blacklisted_resp

        # Run the wrapped view, and capture the data returned.
        response = f(request, *args, **kwargs)

        # If the view returns a string (or a ``twilio.Verb`` object), we'll
        # assume it is XML TwilML data and pass it back with the appropriate
        # mimetype. We won't check the XML data because that would be too time
        # consuming for every request. Instead, we'll let the errors pass
        # through to be dealt with by the developer.
        if isinstance(response, str):
            return HttpResponse(response, mimetype='application/xml')
        elif isinstance(response, Verb):
            return HttpResponse(str(response), mimetype='application/xml')
        else:
            return response
开发者ID:bronfman,项目名称:django-twilio,代码行数:59,代码来源:decorators.py


示例8: _wrapped_view

 def _wrapped_view (request, *args, **kwargs):
     validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)
     url = settings.TWILIO_CALLBACK_URL
     post = request.POST
     signature = request.META.get("HTTP_X_TWILIO_SIGNATURE")
     if not validator.validate(url, post, signature):
         return HttpResponse("Invalid call. Are you twilio?")
     return view_func(request, *args, **kwargs)
开发者ID:fodasign,项目名称:shiftor.co,代码行数:8,代码来源:sms.py


示例9: decorator

    def decorator(request_or_self, *args, **kwargs):

        class_based_view = not isinstance(request_or_self, HttpRequest)
        if not class_based_view:
            request = request_or_self
        else:
            assert len(args) >= 1
            request = args[0]

        # Turn off Twilio authentication when explicitly requested, or
        # in debug mode. Otherwise things do not work properly. For
        # more information, see the docs.
        use_forgery_protection = getattr(
            settings,
            'DJANGO_TWILIO_FORGERY_PROTECTION',
            not settings.DEBUG,
        )
        if use_forgery_protection:

            if request.method not in ['GET', 'POST']:
                return HttpResponseNotAllowed(request.method)

            # Forgery check
            try:
                validator = RequestValidator(TWILIO_AUTH_TOKEN)
                url = request.build_absolute_uri()
                signature = request.META['HTTP_X_TWILIO_SIGNATURE']
            except (AttributeError, KeyError):
                return HttpResponseForbidden()

            if request.method == 'POST':
                if not validator.validate(url, request.POST, signature):
                    return HttpResponseForbidden()
            if request.method == 'GET':
                if not validator.validate(url, request.GET, signature):
                    return HttpResponseForbidden()

        # Blacklist check, by default is true
        check_blacklist = getattr(
            settings,
            'DJANGO_TWILIO_BLACKLIST_CHECK',
            True
        )
        if check_blacklist:
            blacklisted_resp = get_blacklisted_response(request)
            if blacklisted_resp:
                return blacklisted_resp

        response = f(request_or_self, *args, **kwargs)

        if isinstance(response, (text_type, bytes)):
            return HttpResponse(response, content_type='application/xml')
        elif isinstance(response, Verb):
            return HttpResponse(str(response), content_type='application/xml')
        else:
            return response
开发者ID:DuriDuri,项目名称:zagster,代码行数:56,代码来源:decorators.py


示例10: TwiMLTest

class TwiMLTest(unittest.TestCase):
    def setUp(self):
        self.app = app.test_client()
        self.validator = RequestValidator(app.config['TWILIO_AUTH_TOKEN'])

    def assertTwiML(self, response):
        self.assertTrue("<Response>" in response.data, "Did not find " \
                "<Response>: %s" % response.data)
        self.assertTrue("</Response>" in response.data, "Did not find " \
                "</Response>: %s" % response.data)
        self.assertEqual("200 OK", response.status)

    def sms(self, body, url='/sms', to=app.config['TWILIO_CALLER_ID'],
            from_='+15558675309', extra_params=None, signed=True):
        params = {
            'SmsSid': 'SMtesting',
            'AccountSid': app.config['TWILIO_ACCOUNT_SID'],
            'To': to,
            'From': from_,
            'Body': body,
            'FromCity': 'BROOKLYN',
            'FromState': 'NY',
            'FromCountry': 'US',
            'FromZip': '55555'}
        if extra_params:
            params = dict(params.items() + extra_params.items())
        if signed:
            abs_url = 'http://{0}{1}'.format(app.config['SERVER_NAME'], url)
            signature = self.validator.compute_signature(abs_url, params)
            return self.app.post(url, data=params,
                                headers={'X-Twilio-Signature': signature})
        return self.app.post(url, data=params)

    def call(self, url='/voice', to=app.config['TWILIO_CALLER_ID'],
            from_='+15558675309', digits=None, extra_params=None, signed=True):
        params = {
            'CallSid': 'CAtesting',
            'AccountSid': app.config['TWILIO_ACCOUNT_SID'],
            'To': to,
            'From': from_,
            'CallStatus': 'ringing',
            'Direction': 'inbound',
            'FromCity': 'BROOKLYN',
            'FromState': 'NY',
            'FromCountry': 'US',
            'FromZip': '55555'}
        if digits:
            params['Digits'] = digits
        if extra_params:
            params = dict(params.items() + extra_params.items())
        if signed:
            abs_url = 'http://{0}{1}'.format(app.config['SERVER_NAME'], url)
            signature = self.validator.compute_signature(abs_url, params)
            return self.app.post(url, data=params,
                                headers={'X-Twilio-Signature': signature})
        return self.app.post(url, data=params)
开发者ID:zacharyvoase,项目名称:Twilio-Hackpack-for-Heroku-and-Flask,代码行数:56,代码来源:test_twilio.py


示例11: dec

 def dec(request, *args, **kwargs):
     signature = request.META.get('HTTP_X_TWILIO_SIGNATURE', '')
     data = dict()
     for k, v in request.REQUEST.items():
         data[k] = v
     validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)
     if validator.validate(settings.TWILIO_URL, data, signature):
         return func(request, *args, **kwargs)
     else:
         return HttpResponse(status=401)
开发者ID:kel1010,项目名称:needsreport,代码行数:10,代码来源:__init__.py


示例12: twilio_validator_function

def twilio_validator_function(request):
    """returns true for authentic Twilio request, false for unauthenticated request"""
    validator = RequestValidator(app.config['TWILIO_AUTH_TOKEN'])
    URL = request.url
    params = {}
    if request.method == 'POST':
        params = request.values
    else:
        params = request.args
    twilio_signature = request.headers.get('X-Twilio-Signature')
    return validator.validate(URL, params, twilio_signature)
开发者ID:pnguyen90,项目名称:PhoneBuzzApp,代码行数:11,代码来源:phone_buzz_app.py


示例13: decorator

 def decorator(*args, **kwargs):
     if not current_app.config['DEBUG']:
         validator = RequestValidator(current_app.config['TWILIO_AUTH_TOKEN'])
         if not validator.validate(request.url, request.form, request.headers['HTTP_X_TWILIO_SIGNATURE']):
             abort(401)
     response = f(*args, **kwargs)
     if isinstance(response, Verb):
         response = str(response)
     response = make_response(response)
     response.mimetype = 'application/xml'
     return response
开发者ID:jalaziz,项目名称:doorman,代码行数:11,代码来源:decorators.py


示例14: decorator

    def decorator(request, *args, **kwargs):
        # Attempt to gather all required information to allow us to check the
        # incoming HTTP request for forgery. If any of this information is not
        # available, then we'll throw a HTTP 403 error (forbidden).

        # Ensure the request method is POST
        if request.method != "POST":
            logger.error(
                "Twilio: Expected POST request", extra={"request": request})
            return HttpResponseNotAllowed(request.method)

        if not getattr(settings, "TWILIO_SKIP_SIGNATURE_VALIDATION"):
            # Validate the request
            try:
                validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)
                url = request.build_absolute_uri()
                # Ensure the original requested url is tested for validation
                # Prevents breakage when processed behind a proxy server
                if "HTTP_X_FORWARDED_SERVER" in request.META:
                    protocol = "https" if request.META[
                        "HTTP_X_TWILIO_SSL"] == "Enabled" else "http"
                    url = "{0}://{1}{2}".format(
                        protocol, request.META[
                            "HTTP_X_FORWARDED_SERVER"], request.META["REQUEST_URI"]
                    )
                signature = request.META["HTTP_X_TWILIO_SIGNATURE"]
            except (AttributeError, KeyError) as e:
                logger.exception(
                    "Twilio: Missing META param", extra={"request": request})
                return HttpResponseForbidden("Missing META param: %s" % e)

            # Now that we have all the required information to perform forgery
            # checks, we'll actually do the forgery check.
            if not validator.validate(url, request.POST, signature):
                logger.error(
                    "Twilio: Invalid url signature %s - %s - %s",
                    url, request.POST, signature, extra={"request": request}
                )
                return HttpResponseForbidden("Invalid signature")

        # Run the wrapped view, and capture the data returned.
        response = f(request, *args, **kwargs)

        # If the view returns a string (or a ``twilio.Verb`` object), we'll
        # assume it is XML TwilML data and pass it back with the appropriate
        # mimetype. We won't check the XML data because that would be too time
        # consuming for every request. Instead, we'll let the errors pass
        # through to be dealt with by the developer.
        if isinstance(response, six.text_type):
            return HttpResponse(response, mimetype="application/xml")
        elif isinstance(response, Verb):
            return HttpResponse(force_text(response), mimetype="application/xml")
        else:
            return response
开发者ID:theskumar,项目名称:django-twilio-sms-2,代码行数:54,代码来源:decorators.py


示例15: post

	def post(self):
		text = self.get_argument("Body")
		sender = self.get_argument("From").lstrip("+")
		number = self.get_argument("To").lstrip("+")
		signature = self.request.headers.get('X-Twilio-Signature')
		proto = self.request.headers.get('X-Forwarded-Proto', self.request.protocol ) 
		url = proto + "://"+ self.request.host + self.request.path
		var = self.request.arguments
		for x in var:
			var[x] = ''.join(var[x])
		creds = get_creds(number)
		validator = RequestValidator(creds[1])
		if validator.validate(url, var, signature):
			r = twiml.Response()
			if isadmin(sender, number):
				client = TwilioRestClient(creds[0], creds[1])
				gc = gspread.authorize(credentials)
				worksheet = gc.open(number).worksheet("members")
				members = worksheet.col_values(1)
				members = filter(None, members)
				for member in members:
					client.messages.create(body=text, to_=member, from_=number)
				r.message("Mesaage sent to %s recipients" % len(members))
			else:
				if re.match("^start*", text.lower()):
					gc = gspread.authorize(credentials)
					membersheet = gc.open(number).worksheet("members")
					name = text.lower().lstrip("start").lstrip().capitalize()
					membersheet.append_row([sender, name])
					r.message("Thankyou, you have been added to the list")
				elif re.match("^stop*", text.lower()):
					gc = gspread.authorize(credentials)
					membersheet = gc.open(number).worksheet("members")
					try:
						cell = membersheet.find(sender)
						membersheet.update_cell(cell.row, cell.col, '')
						r.message("You have been removed")
					except:
						r.message("Sorry you are not subscribed on this number")
				else:
					if ismember(sender, number):
						gc = gspread.authorize(credentials)
						membersheet = gc.open(number).worksheet("replies")
						membersheet.append_row([timestamp('%Y-%m-%d %H:%M:%S'), sender, text])
					else:
						r.message("Sorry you are not subscribed to this list")
			self.content_type = 'text/xml'
			self.write(str(r))
			self.finish()
		else:
			self.clear()
			self.set_status(403)
			self.finish("INVALID SOURCE")
开发者ID:sammachin,项目名称:smslistsheet,代码行数:53,代码来源:app.py


示例16: validate_twiml

def validate_twiml():
    twilio_signature = request.get_header('X-Twilio-Signature')
    params = request.forms
    url = application.config.Twiml.callback_base_url + request.fullpath
    auth_token = application.config.Twilio.auth_token
    validator = RequestValidator(auth_token)
    validation = validator.validate(url, params, twilio_signature)
    log.debug("Validator: {}".format(validation))
    log.debug("Twilio-signature: {}\r".format(twilio_signature) + \
              "Params: {}\r".format(params) + \
              "Url: {}".format(url))
    return validation
开发者ID:tzakrajs,项目名称:bridgebeam,代码行数:12,代码来源:twiml.py


示例17: verify_request

    def verify_request(self):
        'verify request comes from Twilio'
        # this bit taken from Randal Degges' django-twilio library, which as of
        # 1c020e2a7c6f4845e7309d7277380c8b76d38ba4 has been released into the
        # public domain
        try:
            validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)
            url = self.request.build_absolute_uri()
            signature = self.request.META['HTTP_X_TWILIO_SIGNATURE']
        except (AttributeError, KeyError):
            raise PermissionDenied()

        if not validator.validate(url, self.request.POST, signature):
            raise PermissionDenied()
开发者ID:continuumgroup,项目名称:continuum,代码行数:14,代码来源:twilioview.py


示例18: _wrapped_view

 def _wrapped_view(request, *args, **kwargs):
     backend = kwargs.get('backend_name', backend_name)
     config = settings.INSTALLED_BACKENDS[backend]['config']
     validator = RequestValidator(config['auth_token'])
     signature = request.META.get('HTTP_X_TWILIO_SIGNATURE', '')
     url = request.build_absolute_uri()
     body = {}
     if request.method == 'POST':
         body = request.POST
     require_validation = config.get('validate', True)
     if validator.validate(url, body, signature) or not require_validation:
         return view_func(request, *args, **kwargs)
     else:
         return HttpResponseBadRequest()
开发者ID:lsgunth,项目名称:rapidsms-twilio,代码行数:14,代码来源:views.py


示例19: valid

	def valid(self):
		url = self.request.url
		logging.info("Validating url:" + url)
		validator = RequestValidator(secrets.AUTH_TOKEN)
		params = {}
		logging.info("Validating parameters: ")
		for name in self.request.arguments():
			params[name] = self.request.get(name);
			logging.info(name + ': ' + params[name])
		try:
			signature = self.request.headers["X-Twilio-Signature"]
			logging.info('Validating signature: %s' % signature)
		except KeyError:
			 logging.info('Could not find X-Twilio-Signature, validation will fail.')
		return validator.validate(url, params, signature)
开发者ID:Kagee,项目名称:soppmiddag,代码行数:15,代码来源:trh.py


示例20: send

    def send(self, method, url, authtoken):
        validator = RequestValidator(authtoken)
        params = urllib.urlencode(self.url_params)
        if method == "GET":
            url = "{0}?{1}".format(url, params)
            sig = validator.compute_signature(url, {})
            req = urllib2.Request(url)
        elif method == "POST":
            sig = validator.compute_signature(url, self.url_params)
            req = urllib2.Request(url, params)
        else:
            raise CwurlioUserException("Invalid method: %s" % method)

        req.add_header("X-Twilio-Signature", sig)
        return urllib2.urlopen(req).read()
开发者ID:chadselph,项目名称:cwurlio,代码行数:15,代码来源:http.py



注:本文中的twilio.util.RequestValidator类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python util.TwilioCapability类代码示例发布时间:2022-05-27
下一篇:
Python voice_response.VoiceResponse类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap