Auto validate a function parameter using a method - python

Is there any way to attach a decorator to the following function in Python 3 in order to save having to call _is_valid_token()? I will be passing this static value into every function as a key to call the API via SSL and wish to simplify my code.
# Constants
TOKEN = '7632ba6a-0609-4b0c-a92e-9107bec88941'
#app.route('/my-game-server/api/v1.0/create_new_game/<token>/<player1>/<player2>/<rules>',
methods=['GET'])
def create_new_game(token, player1, player2, rules):
# Create
"""Creates a new game from scratch
:param token: Unique value that verifies the caller is valid
:param player1: Name of the first player
:param player2: Name of the second player
:param rules: String representing the rules to be used in the game
:return: UUID representing the game id that has been created
"""
# Validate token
_is_valid_token(token)
# Create game
game_id = str(uuid.uuid4())
return game_id
def _is_valid_token(token):
"""Validate that the caller has a legitimate call into the service
:param token: Unique value that verifies the caller is valid
"""
if token != TOKEN:
abort(400)

You can use a url processor.
#app.url_value_preprocessor
def _is_valid_token(endpoint, values):
if 'token' not in values:
return
if values['token'] != TOKEN:
abort(400)
This runs for all routes, but only does the validation if the route actually has a 'token' value. There are of course many other checks you could do beforehand to limit validation, such as basing it on specific endpoint names, but this is the most general function.
You can also just decorate the specific functions you want to validate. This would be more general than the Flask solution.
def _is_valid_token(f):
#wraps(f)
def decorated(token, *args, **kwargs):
if token != TOKEN:
abort(400)
return f(token, *args, **kwargs):
return decorated
#app.route(...)
#_is_valid_token
def create_new_game(token, ...):
...

You can always define your own function decorator! This article talks more about decorators in Python:
http://python-3-patterns-idioms-test.readthedocs.org/en/latest/PythonDecorators.html
You could define your decorator as a function like so:
def validate_token(func):
def newfunc(token, *args):
_is_valid_token(token)
return func(token, *args)
return newfunc
...
#validate_token
def create_new_game(token, player1, player2, rules):
...
Now whenever create_new_game is called, it'll call _is_valid_token first, as long as it has the decorator.

Related

Python decorator class with members

I want to write a class that will have member variables and member functions that will be used as decorators.
class decorator_class:
def __init__(self, baseurl, username,password):
self._baseurl = baseurl
self._username = _username
self._password = _password
def decorator_get(self,arguments):
def inner_function(function):
#wraps(function)
def wrapper(*args, **kwargs):
url = self._url + argument
if len(kwargs) > 0:
url+="?"
argseperator=""
for k,v in kwargs.items():
url+="{}{}={}".format(argseperator,k,v)
argseperator="&"
r = requests.get(url, auth=(self._username, self._password))
if r.status_code != 200:
raise Exception('Failed to GET URL: {}'.format(url))
return function(args[0],json = r.json())
return wrapper
return inner_function
class usedecorator:
def __init__(baseurl, self,user,password):
self.dec = decorator_class(baseurl, self,user,password)
#dec.decorator_get('/path/to/resource1')
def process_output_resource1(self, json):
do_something_with_json
The problem is that __init__ is being called after the class is loaded and at that time dec is undefined.
if I define the decorator_class globally it works, but then there is no way to pass the url, user and password to it at runtime.
Any suggestions?
Your decorator_get > innder_function > wrapper has the userdecorator's self.
Weird sentence but eh.
You have some weird namings, IDK why did you use self as a second argument for instance but, I tried to follow your naming.
def decorator_get(arguments):
def inner_function(function):
#wraps(function)
def wrapper(self, *args, **kwargs):
url = self._base_url + arguments
if len(kwargs) > 0:
url+="?"
argseperator=""
for k,v in kwargs.items():
url+="{}{}={}".format(argseperator,k,v)
argseperator="&"
r = requests.get(url, auth=(self._username, self._password))
if r.status_code != 200:
raise Exception('Failed to GET URL: {}'.format(url))
return function(self, json = r.json())
return wrapper
return inner_function
class usedecorator:
def __init__(self, baseurl,user,password):
self._base_url = baseurl
self._username = user
self._password= password
#decorator_get('/path/to/resource1')
def process_output_resource1(self, json):
do_something_with_json
Indeed -to have a decorator for methods in a class, it must already be defined (i.e. ready to be used) when the method to be decorated is declared: which means it have to be declared either at top-level or inside the class body.
Code inside methods, including __init__, however will only run when an instance is created - and that is the point where the class will get your connection parameters.
If this decorator is being used always in this model, you can turn it into a descriptor: an object which is a class attribute, but which has code (in a method named __get__) that is executed after the instance is created.
This descriptor could then fetch the connection parameters in the instance itself, after it has been created, and prepare way for calling the underlying method.
That will require some reorganization on your code: the object returned by __get__ has to be a callable which will ultimately run your function, but it would not be nice if simply retrieving the method name would trigger the network request - one will expect it to be triggered when the process_output... method is actually called. The __get__ method then should return your inner "wrapper" function, which will have all the needed data for the request from the "instance" attribute Python passes automatically, but for the payload which it gets via kwargs.
class decorator_class:
def __init__(self, path=None):
self.path = None
self.func = None
def __get__(self, instance, owner):
if instance is None:
return self
def bound_to_request(**kwargs):
# retrieves the baseurl, user and password from the host instance:
# build query part of the target URL - instead of your convoluted
# code to build the query string (which will break ont he first special character,
# just pass kwargs as the "params" argument)
response = requests.get(instance._base_url, auth=(
instance.user, instance.password), params=kwargs)
# error treatment code
#...
return self.func(response.json())
return bound_to_request
def __call__(self, arg):
# create a new instance of this class on each stage:
# first anotate the API path, on the second call annotate the actual method
new_inst = type(self)()
if not self.path:
if not isinstance(arg, str):
raise TypeError("Expecting an API path for this method")
new_inst.path = arg
else:
if not callable(arg):
raise TypeError("Expecting a target method to be decorated")
new_inst.func = wraps(arg)
return new_inst
def __repr__(self):
return f"{self.func.__name__!r} method bound to retrieve data from {self.path!r}"
class use_decorator:
dec = decorator_class()
def __init__(self=, baseurl, user, password):
# the decorator assumes these to be set as instance attributes
self.baseurl = baseurl
self.user = user
self.password = password
# <- the call passing the path returns an instance of
# the decorator with the path set. it is use as an
# decorator is called again, and on this second call, the decorated method is set.
#dec.decorator_get('/path/to/resource1')
def process_output_resource1(self, json):
# do_something_with_json
...
In time, re-reading your opening paragraph, I see you intended to have more than one decorator inside your original class, probably others intended for "POST" and other HTTP requests: most important thing, the __get__ name here has nothing to do with HTTP: it is a fixed method name in the Python spec which is called automatically by the language when one will retrieve your method from an instance of use_decorator. That is, when there is code: my_instance.process_output_resource1(...), the __get__ method of the descriptor is called. Whatever it returned is then called.
For enabling the same decorator to use POST and other HTTP methods, I suggest you to have as a first parameter when annotating the path for each method, and then simply call the appropriate requests method by checking self.method inside the bound_to_request function.
I think you're going too far with the decorator approach. Let's break this down into a single question: What is the actual shared state here that you need a class for? To me, it looks like just the baseurl, user, and password. So let's just use those directly without a decorator:
from requests import Session
from requests.auth import HTTPBasicAuth
class UseDecorator: # this isn't a good name, but we will keep it temporarily
def __init__(self, baseurl, user, password):
self.baseurl = baseurl
self.session = Session()
# we've now bound the authentication to the session
self.session.auth = HTTPBasicAuth(user, password)
# now let's just bind a uri argument to a function to simply
# send a request
def send_request(self, uri, *args, **kwargs):
url = self.baseurl + uri
# you don't need to manually inject parameters, just use
# the params kwarg
r = self.session.get(url, params=kwargs)
# this will check the response code for you and even handle
# a redirect, which your 200 check will fail on
r.raise_for_status()
return r.json()
# then just handle each individual path
def path_1(self, *args, **kwargs):
data = self.send_request('/path/1', *args, **kwargs)
# process data
def path_2(self, *args, **kwargs):
data = self.send_request('/path/2', *args, **kwargs)
# process data
Because we're leveraging the machinery offered to us by requests, most of your decorator is simplified, and we can boil it down to a simple function call for each path

Python3 "Class factory" - ex: API(token).MyClass()

I'm writing a python REST client for an API.
The API needs authentication and I would like to have many API client objects running on the same script.
My current code for the API is something like this:
class RestAPI:
def __init__(self, id):
self.id = id
self.fetch()
def fetch(self):
requests.get(self.url+self.id, auth=self.apikey)
class Purchase(RestAPI):
url = 'http://example.com/purchases/'
class Invoice(RestAPI):
url = 'http://example.com/invoices/'
...
And I would like to use the API like that:
api_admin = Api('adminmytoken')
api_user = Api('usertoken')
…
amount = api_admin.Purchase(2).amount
api_user.Purchase(2).amount # raises because api_user is not authorized for this purchase
The problem is that each object needs to know it's apikey depending on the client I want to use.
That pattern looks like to me to a "class factory": all the classes of RestAPI need to know of the provided token.
How is it possible to cleanly do that without giving manually the token to each model ?
I think the issue here is that your design is a little backwards. Inheritance might not be the key here. What I might do is take the api token as an argument on the User class, then that gets passed to an instance-level binding on the Rest interface:
class APIUser:
def __init__(self, id, api_key, **kwargs):
self._rest = Interface(id, api_key, **kwargs)
def purchase(self, some_arg):
# the interface itself does the actual legwork,
# and you are simply using APIUser to call functions with the interface
return self._rest.fetch('PURCHASE', some_arg)
class Interface:
methods = {
# call you want (class url)
'PURCHASE': (Purchase, 'https://myexample.com/purchases'),
'INVOICE': (Invoice, 'https://myexample.com/invoices'),
# add more methods here
}
def __init__(self, id, key):
self.id = id
self.key = key
self.session = requests.Session()
def _fetch(self, method, *args, **kwargs):
# do some methods to go get data
try:
# use the interface to look up your class objects
# which you may or may not need
_class, url = self.methods[method]
except KeyError as e:
raise ValueError(f"Got unsupported method, expected "
f"{'\n'.join(self.methods)}") from e
headers = kwargs.pop('headers', {})
# I'm not sure the actual interface here, maybe you call the
# url to get metadata to populate the class with first...
req = requests.Request(_class.http_method, url+self.id, auth=self.key, headers=headers).prepare()
resp = self.session.send(req)
# this will raise the 401 ahead of time
resp.raise_for_status()
# maybe your object uses metadata from the response
params = resp.json()
# return the business object only if the user should see it
return _class(*args, **kwargs, **params)
class Purchase:
http_method = 'GET'
def __init__(self, *args, **kwargs):
# do some setup here with your params passed by the json
# from the api
user = APIUser("token", "key") # this is my user session
some_purchase = user.purchase(2) # will raise a 401 Unauthorized error from the requests session
admin = APIUser("admintoken", "adminkey") # admin session
some_purchase = admin.purchase(2)
# returns a purchase object
some_purchase.amount
There are a few reasons why you might want to go this way:
You don't get the object back if you aren't allowed to see it
Now the rest interface is in control of who sees what, and that's implicitly tied to the user object itself, without every other class needing to be aware of what's going on
You can change your url's in one place (if you need to)
Your business objects are just business objects, they don't need to do anything else
By separating out what your objects actually are, you still only need to pass the api keys and tokens once, to the User class. The Interface is bound on the instance, still giving you the flexibility of multiple users within the same script.
You also get the models you call on explicitly. If you try to take a model, you have to call it, and that's when the Interface can enforce your authentication. You no longer need your authentication to be enforced by your business objects

Python: run staticmethod of class in init?

The following is making me suspect whether what I want is a class or a module.
Basically I'm building a parser of sorts, an API library.
The external service which my code connects to needs a token for every time a request is made.
I'm successfully generating this token. However, I'm not sure how I can "give" this token to class instances if it's not in the __init__ of the class.
My code so far:
class MBParser(object):
pass
class SomeServiceParser(MBParser):
'''instantiate and use me'''
def __init__(self):
self.token = _get_token()
#staticmethod
def _get_token():
# code to get the token
You could wrap each function that requires a new token in a decorator like the following:
def new_token(func):
def wrapper(self, *args, **kwargs):
self.token = SomeParser._get_token()
r = func(self, *args, **kwargs)
return wrapper
I explicitly added a self argument in the wrapper method since the methods in the class will need this anyway. And this way, I can access the self.token attribute and set it to a new value
Could use the decorator as follows:
#new_token
def makeHTTPRequest(self, name):
# ... make request and use self.token here

Perform additional operations for each call to an external API

I have an external API that I cannot modify. For each call to this API, I need to be able to perform an operation before and after. This API is used like this:
def get_api():
"""
Return an initiated ClassAPI object
"""
token = Token.objects.last()
api = ClassAPI(
settings.CLASS_API_ID,
settings.CLASS_API_SECRET,
last_token)
return api
get_api() is called everywhere in the code and the result is then used to perform request (like: api.book_store.get(id=book_id)).
My goal is to return a virtual object that will perform the same operations than the ClassAPI adding print "Before" and print "After".
The ClassAPI looks like this:
class ClassAPI
class BookStore
def get(...)
def list(...)
class PenStore
def get(...)
def list(...)
I tried to create a class inheriting from (ClassApi, object) [as ClassAPI doesn't inherit from object] and add to this class a metaclass that decorates all the methods, but I cannot impact the methods from BookStore (get and list)
Any idea about how to perform this modifying only get_api() and adding additional classes? I try to avoid copying the whole structure of the API to add my operations.
I am using python 2.7.
You could do this with a Proxy:
class Proxy:
def __init__(self, other):
self.other = other
self.calls = []
def __getattr__(self, name):
self.calls.append(name)
return self
def __call__(self, *args, **kwargs):
self.before()
ret = self.call_proxied(*args, **kwargs)
self.after()
return ret
def call_proxied(self, *args, **kwargs):
other = self.other
calls = self.calls
self.calls = []
for item in calls:
other = getattr(other, item)
return other(*args, **kwargs)
This class intercepts unknown members in the __getattr__() method, saving the names that are used and returning itself.
When a method is called (eg. api.book_store.get(id=book_id) ), it calls a before() and after() method on itself and in between it fetches the members of other and forwards the arguments in a call.
You use this class like this:
def get_api():
...
return Proxy(api)
Update: corrected the call to self.call_proxied(*args, **kwargs). Also allow any return value to be returned.

How to transfer url parameters to repoze custom predicate checkers

I would like to create a repoze custom predicate checker that is capable to access url parameters and validate something. But I would like to use allow_only to set this permission checker in all the controller's scope. Something like:
class MyController(BaseController):
allow_only = All(not_anonymous(msg=l_(u'You must be logged on')),
my_custom_predicate(msg=l_(u'something wrong')))
def index(self, **kw):
return dict()
then, my_custom_predicate should check the url paramters for every request in every MyController method, and do whatever it do.
The problem is just that: how to allow my_custom_predicate to check the url parameters, using it in that way I wrote above.
May be you need to use ControllerProtector
from repoze.what.plugins.pylonshq import ControllerProtector
allow_only = All(not_anonymous(msg=l_(u'You must be logged on')),
my_custom_predicate(msg=l_(u'something wrong')))
#ControllerProtector(allow_only)
class MyController(BaseController):
def index(self, **kw):
return dict()
See docs at http://code.gustavonarea.net/repoze.what-pylons/API.html

Categories

Resources