Setup SUSI Assistant on Raspberry Pi in under 30 minutes

With our ever growing list of list of platforms supported by Susi AI, we now have a client that can run on Raspberry Pi and you can access it hands-free!! Here is a video that you can refer for its working. https://youtu.be/au0MAc0GF6w But it might have left you wondering how you can replicate such a setup yourself? It is fairly easy and will be done fairly easy. Just follow the following instructions. You need to have following hardware in order to have your own SUSI Assistant running on Raspberry Pi. A Raspberry Pi (prefer 2 or 3) with Raspbian Jessie OS. A stable internet connection.  ( Recommended 4 Mbps ) A USB Microphone /  USB Webcam with Microphone. You may buy one like this. A Speaker that connects through 3.5mm jack. You may buy one like this. After you get all the above items in order, you need to get access to a terminal of your Raspberry Pi. You can have that by either connecting a monitor to Raspberry Pi temporarily or by connecting to Raspberry Pi over SSH. Once this is done, next step is the installation of the dependencies. The installation of the SUSI on Raspberry is automated after dependencies are installed. Run the following command on Raspberry Pi terminal. sudo apt install git swig3.0 portaudio19-dev pulseaudio libpulse-dev unzip sox libatlas-dev libatlas-base-dev libsox-fmt-all python3 After this, you may check if your output and input devices are working alright. For this, run rec recording.wav . It will start recording audio and saving it to a file named recording.wav. Play back the file using play recording.wav If you hear your audio clearly, setup is done right else you need to configure your Audio Devices correctly.  Most of the time the configuration of Audio works out the box and devices are plug and play so you would not encounter any errors. If you are successful in configuring your devices, install extra dependencies for SUSI Hardware by running the automated install script. In your terminal run, $ git clone https://github.com/fossasia/susi_hardware.git $ cd susi_hardware $ ./install.sh This will install all the remaining dependencies. After the above step is complete, you may run configuration file generator script to choose the Text to Speech and Speech to Text service according to your wish. For doing so, you need to run $ python3 config_generator.py Follow the instructions in the script. It will ask you to configure the default service for Text to Speech and Speech to Text and other options. After the configuration is complete, you can simply run the following command to start SUSI. $ python3 main.py This will start SUSI in a continuously listening mode. You may invoke SUSI anytime, just by saying SUSI followed by a query. The query will be answered by SUSI subsequently. Since configurations for different hardware devices may vary, you may encounter some problems. In such a scenario, you may refer to the following resources to solve the issues. Resources: For Setting up Audio properly: - Debian Pulseaudio setup guide. For setting up…

Continue ReadingSetup SUSI Assistant on Raspberry Pi in under 30 minutes

Building the Meilix Generator with Flask

Meilix Generator is a webapp which is used to trigger the Travis build of Meilix and mail the user the link of the iso. Meilix Generator webapp is based on Flask. This blog shows that how easy is to build a webapp and take the HTML files to render it into the webapp as well as to call and pass various function. Here I used Flask, the Python framework to render the HTML templates and send requests for various purposes (mentioned later in the article) without coding everything from scratch because of import facility of the Flask. What is Flask? Flask is a Python micro web framework based on Werkzeug, Jinja 2 template engine. It is used as the backbone of the webapp. It features us with a whole set of Python from which we can easily generate webapp. It is micro as it has no tools and no library itself. It come up with minimum requirements and one who needs can import different library and use it. And I used several import function for Meilix Generator like render_template, send_from_directory, etc. Implementation (The use case in Meilix Generator) First of all, the installation process: We will do the installation in a virtual environment. We prefer virtual environment to differentiate the Python working environment since few programs are there which require different Python versions to work. Install virtual environment  sudo pip install virtualenv Now go to the folder (project) and activate it using . venv/bin/activate Now install Flask pip install flask Creating your project Now it’s time to create a simple project in the directory. Let’s use HTML as the frontend. In the folder create styles.css for styling and index.html template for the frontend of the page.We will make one app.py file which would look similar to this:  from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): """Index page""" return render_template("index.html") if __name__ == '__main__': app.run() Flask looks for the / (root) path and here the root return the main template (index.html) which is the main function. Compiling it to view the page: export FLASK_DEBUG=1 FLASK_APP=app.py flask run You will find your page at http://127.0.0.1:5000 More options (how more it can help you) Add more HTML template options and refer it in app.py Easily use Github API  from a different .py file (this file should get import to app.py) to fetch data like: https://api.github.com/users/user_name : It will fetch user name, repos, followers and many more important information. How I used this idea for FOSSASIA (Meilix Generator) I used Flask for the backbone of project Meilix Generator. First, I used from function to import various library needed for the project and then made several functions for the same. Let’s understand the concept using few example: from flask import Flask, render_template @app.route('/about') def about(): #About page return render_template("about.html") or from flask import Flask, send_from_directory @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'],filename) For more details file app.py can be found here of the Meilix Generator repository where we used the above idea. Important Links…

Continue ReadingBuilding the Meilix Generator with Flask

Testing Errors and Exceptions Using Unittest in Open Event Server

Like all other helper functions in FOSSASIA's Open Event Server, we also need to test the exception and error helper functions and classes. The error helper classes are mainly used to create error handler responses for known errors. For example we know error 403 is Access Forbidden, but we want to send a proper source message along with a proper error message to help identify and handle the error, hence we use the error classes. To ensure that future commits do not mismatch the error, we implemented the unit tests for errors. There are mainly two kind of error classes, one are HTTP status errors and the other are the exceptions. Depending on the type of error we get in the try-except block for a particular API, we raise that particular exception or error. Unit Test for Exception Exceptions are written in this form: @validates_schema def validate_quantity(self, data): if 'max_order' in data and 'min_order' in data: if data['max_order'] < data['min_order']: raise UnprocessableEntity({'pointer': '/data/attributes/max-order'}, "max-order should be greater than min-order")   This error is raised wherever the data that is sent as POST or PATCH is unprocessable. For example, this is how we raise this error: raise UnprocessableEntity({'pointer': '/data/attributes/min-quantity'},           "min-quantity should be less than max-quantity") This exception is raised due to error in validation of data where maximum quantity should be more than minimum quantity. To test that the above line indeed raises an exception of UnprocessableEntity with status 422, we use the assertRaises() function. Following is the code: def test_exceptions(self): # Unprocessable Entity Exception with self.assertRaises(UnprocessableEntity): raise UnprocessableEntity({'pointer': '/data/attributes/min-quantity'}, "min-quantity should be less than max-quantity") In the above code, with self.assertRaises() creates a context of exception type, so that when the next line raises an exception, it asserts that the exception that it was expecting is same as the exception raised and hence ensures that the correct exception is being raised Unit Test for Error In error helper classes, what we do is, for known HTTP status codes we return a response that is user readable and understandable. So this is how we raise an error: ForbiddenError({'source': ''}, 'Super admin access is required') This is basically the 403: Access Denied error. But with the “Super admin access is required” message it becomes far more clear. However we need to ensure that status code returned when this error message is shown still stays 403 and isn’t modified in future unwantedly. Here, errors and exceptions work a little different. When we declare a custom error class, we don’t really raise that error. Instead we show that error as a response. So we can’t use the assertRaises() function. However what we can do is we can compare the status code and ensure that the error raised is the same as the expected one. So we do this: def test_errors(self): with app.test_request_context(): # Forbidden Error forbidden_error = ForbiddenError({'source': ''}, 'Super admin access is required') self.assertEqual(forbidden_error.status, 403) # Not Found Error not_found_error = NotFoundError({'source': ''}, 'Object not found.') self.assertEqual(not_found_error.status, 404) Here we firstly create an…

Continue ReadingTesting Errors and Exceptions Using Unittest in Open Event Server

Open Event Server: Testing Image Resize Using PIL and Unittest

FOSSASIA's Open Event Server project uses a certain set of functions in order to resize image from its original, example to thumbnail, icon or larger image. How do we test this resizing of images functions in Open Event Server project? To test image dimensions resizing functionality, we need to verify that the the resized image dimensions is same as the dimensions provided for resize.  For example, in this function, we provide the url for the image that we received and it creates a resized image and saves the resized version. def create_save_resized_image(image_file, basewidth, maintain_aspect, height_size, upload_path, ext='jpg', remove_after_upload=False, resize=True): """ Create and Save the resized version of the background image :param resize: :param upload_path: :param ext: :param remove_after_upload: :param height_size: :param maintain_aspect: :param basewidth: :param image_file: :return: """ filename = '{filename}.{ext}'.format(filename=get_file_name(), ext=ext) image_file = cStringIO.StringIO(urllib.urlopen(image_file).read()) im = Image.open(image_file) # Convert to jpeg for lower file size. if im.format is not 'JPEG': img = im.convert('RGB') else: img = im if resize: if maintain_aspect: width_percent = (basewidth / float(img.size[0])) height_size = int((float(img.size[1]) * float(width_percent))) img = img.resize((basewidth, height_size), PIL.Image.ANTIALIAS) temp_file_relative_path = 'static/media/temp/' + generate_hash(str(image_file)) + get_file_name() + '.jpg' temp_file_path = app.config['BASE_DIR'] + '/' + temp_file_relative_path dir_path = temp_file_path.rsplit('/', 1)[0] # create dirs if not present if not os.path.isdir(dir_path): os.makedirs(dir_path) img.save(temp_file_path) upfile = UploadedFile(file_path=temp_file_path, filename=filename) if remove_after_upload: os.remove(image_file) uploaded_url = upload(upfile, upload_path) os.remove(temp_file_path) return uploaded_url In this function, we send the image url, the width and height to be resized to, and the aspect ratio as either True or False along with the folder to be saved. For this blog, we are gonna assume aspect ratio is False which means that we don’t maintain the aspect ratio while resizing. So, given the above mentioned as parameter, we get the url for the resized image that is saved. To test whether it has been resized to correct dimensions, we use Pillow or as it is popularly know, PIL. So we write a separate function named getsizes() within which get the image file as a parameter. Then using the Image module of PIL, we open the file as a JpegImageFile object. The JpegImageFile object has an attribute size which returns (width, height). So from this function, we return the size attribute. Following is the code: def getsizes(self, file): # get file size *and* image size (None if not known) im = Image.open(file) return im.size As we have this function, it’s time to look into the unit testing function. So in unit testing we set dummy width and height that we want to resize to, set aspect ratio as false as discussed above. This helps us to test that both width and height are properly resized. We are using a creative commons licensed image for resizing. This is the code: def test_create_save_resized_image(self): with app.test_request_context(): image_url_test = 'https://cdn.pixabay.com/photo/2014/09/08/17/08/hot-air-balloons-439331_960_720.jpg' width = 500 height = 200 aspect_ratio = False upload_path = 'test' resized_image_url = create_save_resized_image(image_url_test, width, aspect_ratio, height, upload_path, ext='png') resized_image_file = app.config.get('BASE_DIR') + resized_image_url.split('/localhost')[1] resized_width, resized_height = self.getsizes(resized_image_file) In the above code from create_save_resized_image, we receive the url…

Continue ReadingOpen Event Server: Testing Image Resize Using PIL and Unittest

Creating Unit Tests for File Upload Functions in Open Event Server with Python Unittest Library

In FOSSASIA's Open Event Server, we use the Python unittest library for unit testing various modules of the API code. Unittest library provides us with various assertion functions to assert between the actual and the expected values returned by a function or a module. In normal modules, we simply use these assertions to compare the result since the parameters mostly take as input normal data types. However one very important area for unittesting is File Uploading. We cannot really send a particular file or any such payload to the function to unittest it properly, since it expects a request.files kind of data which is obtained only when file is uploaded or sent as a request to an endpoint. For example in this function: def uploaded_file(files, multiple=False): if multiple: files_uploaded = [] for file in files: extension = file.filename.split('.')[1] filename = get_file_name() + '.' + extension filedir = current_app.config.get('BASE_DIR') + '/static/uploads/' if not os.path.isdir(filedir): os.makedirs(filedir) file_path = filedir + filename file.save(file_path) files_uploaded.append(UploadedFile(file_path, filename)) else: extension = files.filename.split('.')[1] filename = get_file_name() + '.' + extension filedir = current_app.config.get('BASE_DIR') + '/static/uploads/' if not os.path.isdir(filedir): os.makedirs(filedir) file_path = filedir + filename files.save(file_path) files_uploaded = UploadedFile(file_path, filename) return files_uploaded So, we need to create a mock uploading system to replicate this check. So inside the unittesting function we create an api route for this particular scope to accept a file as a request. Following is the code: @app.route("/test_upload", methods=['POST']) def upload(): files = request.files['file'] file_uploaded = uploaded_file(files=files) return jsonify( {'path': file_uploaded.file_path, 'name': file_uploaded.filename}) In the above code, it creates an app route with endpoint test_upload. It accepts a request.files. Then it sends this object to the uploaded_file function (the function to be unittested), gets the result of the function, and returns the result in a json format. With this we have the endpoint to mock a file upload ready. Next we need to send a request with file object. We cannot send a normal data which would then be treated as a normal request.form. But we want to receive it in request.files. So we create 2 different classes inheriting other classes. def test_upload_single_file(self): class FileObj(StringIO): def close(self): pass class MyRequest(Request): def _get_file_stream(*args, **kwargs): return FileObj() app.request_class = MyRequest MyRequest class inherits the Request class of Flask framework. We define the file stream of the Request class as the FileObj. Then, we set the request_class attribute of the Flask app to this new MyRequest class. After we have it all setup, we need to send the request and see if the uploaded file is being saved properly or not. For this purpose we take help of StringIO library. StringIO creates a file-like class which can be then used to replicate a file uploading system. So we send the data as {‘file’: (StringIO('1,2,3,4'), 'test_file.csv')}. We send this as data to the /test_upload endpoint that we have created previously. As a result, the endpoint receives the function, saves the file, and returns the filename and file_path for the stored file. with app.test_request_context(): client = app.test_client() resp = client.post('/test_upload',…

Continue ReadingCreating Unit Tests for File Upload Functions in Open Event Server with Python Unittest Library

Characteristization of Transistors Using PSLab

Transistors are one of the key building blocks of all electronics. They are fundamentally three-terminal semiconductor devices, with the terminals being labelled as the Emitter(E), Base(B), and Collector(C). These active components are found everywhere in electronics, and all of the complex processors that power everything from cellphones to aircraft employ millions of these devices in switching and amplification roles. In this blog post, we shall use the PSLab to explore some of the fundamental properties of transistors, and their various applications. Transistor as an amplifier In the schematic shown, we shall try to use an NPN transistor to amplify a small signal. A small amplitude oscillation generated by W1 with the amplitude knob turned down to a very low level is used as the input. Since transistors do not handle bipolar signals, we have mixed a constant DC voltage generated PV3 to shift this small signal into the positive domain. The fluctuating potential difference incident at the base of the transistor creates a corresponding current flow between the Base and Emitter. By the fundamental property of transistors, this influences the path resistance between the Collector(C) and the Emitter(E) , and the resultant amplified voltage output can be monitored at the junction between the 1K resistor and the collector. We have used CH1 to monitor the input voltage, and CH2 for the output In a more applied scenario, we can implement the second schematic in order to create an audio amplifier. Instead of using W1 as the input signal, a speaker is used as a microphone. When a sound signal is incident on the speaker, its membrane oscillates, and as a result , the coil attached to it also does the same. Since this coil is placed in a magnetic field , its oscillations result in a change in the magnetic flux passing through, and this change causes a voltage(EMF) induced at its output. We then use our transistor amplifier to amplify this small EMF Common Emitter Characteristics Any introductory course on transistors includes a diagram similar to the one shown , and a description about how for any base current, the collector current eventually saturates, and that this saturation level is proportional to the base current itself. With the PSLab’s transistor CE characterization app, we can set up this experiment, and verify this for ourselves using an NPN transistor. The results shown were gathered using a 2N2222 transistor In the schematic , the base current is determined by the voltage source PV2, and a high value series resistor of 200 KOhms . We use an analog input CH3 to monitor the voltage present at the Base of the transistor in order to calculate the total base current. Base current = V/R = (PV2 - CH3) / 200e3 Now that we have set a particular base current, PV1 is used to sequentially increase the voltage across the collector and emitter of the transistor. A current limiting resistor of 1K Ohm is used, and CH1 is used to monitor the voltage drop…

Continue ReadingCharacteristization of Transistors Using PSLab

Mailing Attachments Using Terminal in Open Event Android

The latest version of Open Event Android App Generator, v2 lacked the feature of mailing the generated APK to the email ID that is entered at the start of the app generation process. This also included mailing the error logs in case of APK failure. This is an important feature for app generator because the process of app generation is a time taking one. The users have to wait for the app to be generated so that they can download the generated APK. To avoid this, the generator can automatically email the APK as soon as it is generated. I took up this issue a few days back and started working on it. I started with thinking about the ways through which it will be implemented. This required some discussions with the mentors and co-developers. We finalised on the following ways: Using Sendgrid Using SMTP I will be discussing the implementation of both of them in this blog. The code for APK mailing starts with the function call Notification.send in generator.py if completed and apk_path and not error: Notification.send( to=self.creator_email, subject='Your android application for %s has been generated ' % self.event_name, message='Hi,<br><br>' 'Your android application for the \'%s\' event has been generated. ' 'And apk file has been attached along with this email.<br><br>' 'Thanks,<br>' 'Open Event App Generator' % self.event_name, file_attachment=apk_path, via_api=self.via_api ) else: Notification.send( to=self.creator_email, subject='Your android application for %s could not generated ' % self.event_name, message='Hi,<br><br> ' 'Your android application for the \'%s\' event could not generated. ' 'The error message has been provided below.<br><br>' '<code>%s</code><br><br>' 'Thanks,<br>' 'Open Event App Generator' % (self.event_name, str(error) if error else ''), file_attachment=apk_path, via_api=self.via_api ) This leads me to the class Notification.py. It has three functions:- 1. send(to, subject, message, file_attachment, via_api) 2. send_mail_via_smtp(payload): 3. send_email_via_sendgrid(payload): As the name suggests, the first function: send(to, subject, message, file_attachment, via_api) mainly decides which service (out of smtp and sendgrid) should be used to send the email, on the basis of the input parameters (especially, the ‘EMAIL_SERVICE’ parameter that has to be set in config.py). The function looks like as follows: send(to, subject, message, file_attachment, via_api) It is in the send() that the other two functions are called. If the email_service is smtp, it calls the Notification.send_mail_via_smtp(payload). Otherwise, the Notification.send_email_via_sendgrid(payload) is called. The sendgrid function is pretty straightforward: @staticmethod def send_email_via_sendgrid(payload): key = current_app.config['SENDGRID_KEY'] if not key: logger.info('Sendgrid key not defined') return headers = { "Authorization": ("Bearer " + key) } requests.post( "https://api.sendgrid.com/api/mail.send.json", data=payload, headers=headers ) It requires a personalised sendgrid key which is accessed from the config.py file. Apart from that it handles some errors by giving logs in celery tasks. The main line in the function that initiates the email is a POST request made using the python library ‘requests’. The request is made as follows: requests.post( "https://api.sendgrid.com/api/mail.send.json", data=payload, headers=headers ) The send_mail_via_smtp(payload): function looks for some configurations before sending the mail: @staticmethod def send_mail_via_smtp(payload): """ Send email via SMTP :param config: :param payload: :return: """ smtp_encryption = current_app.config['SMTP_ENCRYPTION'] if smtp_encryption == 'tls':…

Continue ReadingMailing Attachments Using Terminal in Open Event Android

Managing Related Endpoints in Permission Manager of Open Event API Server

Open Event API Server has its permission manager to manage all permission to different endpoints and some of the left gaps were filled by new helper method has_access. The next challenge for permission manager was to incorporate a feature many related endpoints points to the same resource. Example: /users-events-roles/<int:users_events_role_id>/user or /event-invoices/<int:event_invoice_id>/user Both endpoints point to Users API where they are fetching the record of a single user and for this, we apply the permission “is_user_itself”. This permission ensures that the logged in user is the same user whose record is asked through the API and for this we need the “user_id” as the “id” in the permission function, “is_user_itself” Thus there is need to add the ability in permission manager to fetch this user_id from different models for different endpoints. For example, if we consider above endpoints then we need the ability to get user_id from UsersEventsRole and EventInvoice models and pass it to permission function so that it can use it for the check. Adding support To add support for multiple keys, we have to look for two things. fetch_key_url model These two are key attributes to add this feature, fetch_key_url will take the comma separated list which will be matched with view_kwargs and model receives the array of the Model Classes which will be used to fetch the related records from the model This snippet provides the main logic for this: for index, mod in enumerate(model): if is_multiple(fetch_key_url): f_url = fetch_key_url[index] else: f_url = fetch_key_url try: data = mod.query.filter(getattr(mod, fetch_key_model) == view_kwargs[f_url]).one() except NoResultFound, e: pass else: found = True if not found: return NotFoundError({'source': ''}, 'Object not found.').respond() From the above snippet we are: We iterate through the models list Check if fetch_key_url has multiple keys or not Get the key from fetch_key_url on the basis of multiple keys or single key in it. We try to attempt to get object from model for the respective iteration If there is any record/object in the database then it’s our data. Skipping further process Else continue iteration till we get the object or to the end. To use multiple mode Instead of providing the single model to the model option of permission manager, provide an array of models. Also, it is optional to provide comma separated values to fetch_key_url Now there can be scenario where you want to fetch resource from database model using different keys present on your view_kwargs for example, consider these endpoints `/notifications/<notification_id>/event` `/orders/<order_id>/event` Since they point to same resource and if you want to ensure that logged in user is organizer then you can use these two things as: fetch_key_url="notification_id, order_id" model=[Notification, Order] Permission manager will always match indexes in both options, the first key of fetch_key_url will be only used for the first key of the model and so on. Also, fetch_key_url is an optional parameter and even in multiple mode you can provide a single value as well.  But if you provide multiple commas separated values make sure you provide all values such…

Continue ReadingManaging Related Endpoints in Permission Manager of Open Event API Server

Custom Data Layer in Open Event API Server

Open Event API Server uses flask-rest-jsonapi module to implement JSON API. This module provides a good logical abstraction in the data layer. The data layer is a CRUD interface between resource manager and data. It is a very flexible system to use any ORM or data storage. The default layer you get in flask-rest-jsonapi is the SQLAlchemy ORM Layer and API Server makes use of default alchemy layer almost everywhere except the case where I worked on email verification part. To add support for adding user’s email verification in API Server, there was need to create an endpoint for POST /v1/users/<int:user_id>/verify Clearly here we are working on a single resource i.e, specific user record. This requires us to use ResourceDetail and the only issue was there is no any POST method or view in ResourceDetail class. To solve this I created a custom data layer which enables me to redefine all methods and views by inheriting abstract class. A custom data layer must inherit from flask_rest_jsonapi.data_layers.base.Base. Creating Custom Layer To solve email verification process, a custom layer was created at app/api/data_layers/VerifyUserLayer.py def create_object(self, data, view_kwargs): user = safe_query(self, User, 'id', view_kwargs['user_id'], 'user_id') s = get_serializer() try: data = s.loads(data['token']) except Exception: raise UnprocessableEntity({'source': 'token'}, "Invalid Token") if user.email == data[0]: user.is_verified = True save_to_db(user) return user else: raise UnprocessableEntity({'source': 'token'}, "Invalid Token") Using custom layer in API We can easily provide custom layer in API Resource using one of the properties of the Resource Class data_layer = { 'class': VerifyUserLayer, 'session': db.session } This is all we have to provide in the custom layer, now all CRUD method will be directed to our custom data layer. Solution to our issue Setting up custom layer provides us the ability to create our custom resource methods, i.e, modifying the view for POST request and allowing us to verify the registered users in API Server. On Setting up the data layer all I need to do is create a ResourceList with using this layer and with permissions class VerifyUser(ResourceList): methods = ['POST', ] decorators = (jwt_required,) schema = VerifyUserSchema data_layer = { 'class': VerifyUserLayer, 'session': db.session } This enables me to use the custom layer, VerifyUserLayer for ResourceList resource. Resources Flask-rest-jsonapi Data layer http://flask-rest-jsonapi.readthedocs.io/en/latest/data_layer.html JSON-API Spec http://jsonapi.org/format/

Continue ReadingCustom Data Layer in Open Event API Server

A guide to use Permission Manager in Open Event API Server

This article provides a simple guide to use permission manager in Open Event API Server. Permission manager is constantly being improved and new features are being added into it. To ensure that all co-developers get to know about it and make use of them, this blog posts describes every part of permission manager. Bootstrapping Permission manager as a part of flask-rest-jsonapi works as a decorator for different resources of the API. There are two ways to provide the permission decorator to any view First one is to provide it in the list of decorators decorators = (api.has_permission('is_coorganizer', fetch="event_id", fetch_as="event_id", model=StripeAuthorization),) Second way is to explicitly provide it as a decorator to any view @api.has_permission('custom_arg', custom_kwargs='custom_kwargs') def get(*args, **kwargs): return 'Hello world !' In the process of booting up, we first need to understand the flow of Resources in API. All resources even before doing any schema check, call the decorators. So this way you will not get any request data in the permission methods. All you will receive is a dict of the URL parameters but again it will not include the filter parameters. Permission Manager receives five parameters as:  def permission_manager(view, view_args, view_kwargs, *args, **kwargs): First three are provided into it implicitly by flask-rest-jsonapi module view: This is the resource’s view method which is called through the API. For example, if I go to /events then the get method of ResourceList will be called. view_args: These are args associated with that view. view_kwargs: These are kwargs associated with that resource view. It includes all your URL parameters as well. args: These are the custom args which are provided when calling the permission manager. Here at permission manager is it expected that the first index of args will be the name of permission to check for. kwargs: This is the custom dict which is provided on calling the permission manager. The main pillar of the permission manager. Described below in usage. Using Permission Manager Using permission manager is basically understanding the different options you can send through the kwargs so here is the list of the things you can send to permission manager These are all described in the order of priority in permission manager method (string): You can provide a string containing the methods where permission needs to be checked as comma separated values of different methods in a string. For example: method=”GET,POST” leave_if (lambda): This receives a lambda function which should return boolean values. Based on returned value if is true then it will skip the permission check. The provided lambda function receives only parameter, “view_kwargs” Example use case can be the situation where you can leave the permission for any specifically related endpoint to some resource and would like to do a manual check in the method itself. check (lambda): Opposite to leave_if. It receives a lambda function that will return boolean values. Based on returned value, If it is true then only it will go further and check the request for permissions else will throw forbidden…

Continue ReadingA guide to use Permission Manager in Open Event API Server