Handling file uploading in HTML5 and Express

The Open Event Webapp Generator has a pure HTML front end form, and Express based backend.

 

We needed an option where users can upload their own JSON files to create a schedule page for it.

On the HTML form that’s easy. As you can see here we simple add input tags with type=”file”


<input type="file" name="sponsorfile" id="sponsorfile">

In our express app, we need to use multer to be able to handle file uploads.

We create a middleware called uploadedFiles, and pass the middleware to the get() block

 

var express = require('express');
var multer = require('multer');
var app = express();

var upload = multer({dest: 'uploads/'});

var uploadedFiles = upload.fields([
  {name: 'speakerfile', maxCount: 1},
  {name: 'sessionfile', maxCount: 1},
  {name: 'trackfile', maxCount: 1},
  {name: 'sponsorfile', maxCount: 1},
  {name: 'eventfile', maxCount: 1},
  {name: 'locationfile', maxCount: 1}
]);

app.post('/live', uploadedFiles, function(req, res) {
         // req.files has the files
         // req.body has the POST body params
  });
});

Now we can access the files inside req.files (that will have a path to the temporary location of the file, you’ll have to use some filesystem module to read the files)

Continue ReadingHandling file uploading in HTML5 and Express

Building interactive elements with HTML and javascript: Resizing

{ Repost from my personal blog @ https://blog.codezero.xyz/building-interactive-elements-with-html-and-javascript-resizing }

Unlike draggable, HTML/js does not provide us with a direct spec for allowing users to graphically resize HTML DOM elements. So, we’ll be using mouse events and pointer locations to achieve the ability of resizing.

We’ll start with a box div.

<div id="box">  
    <div>Resize me !</div>
</div>  

A little bit of CSS magic to make it look a little bit better and square.

#box {
    position: relative;
    width: 130px;
    height: 130px;
    background-color: #2196F3;
    color: white;
    display:flex;
    justify-content:center;
    align-items:center;
    border-radius: 10px;
}

Now, we need a handle element. The user will be using this handle element to drag and resize the box.

<div id="box">  
    <div>Resize me !</div>
    <div id="handle">
    </div>
</div>  

Now, we just have an invisible div. Let’s give it some color, make it square. We also have to position it at one corner of the box.

#handle {
    background-color: #727272;
    width: 10px;
    height: 10px;
    cursor: se-resize;
    position:absolute;
    right: 0;
    bottom: 0;
}

The parent div#box has the CSS property position: relative and by setting div#handle the property position:absolute, we have the ability to position the handle absolutely with respect to its parent.

Also, note the cursor: se-resize property. This instructs the browser to set the cursor to the resize cursor () when the user is over it.

Now, it’s upto to javascript to take over. :wink:

var resizeHandle = document.getElementById('handle');  
var box = document.getElementById('box');  

For resizing, the user would click on the handle and drag it. So, we need to start resizing the moment the user presses and holds on the handle. Let’s setup a function to listen for the mousedown event.

resizeHandle.addEventListener('mousedown', initialiseResize, false);  

the initialiseResize function should do two things:

  1. Resize the box every time the mouse pointer moves.
  2. Listen for mouseup event so that the event listeners can be removed as soon as the user is done resizing.
function initialiseResize(e) {  
    window.addEventListener('mousemove', startResizing, false);
    window.addEventListener('mouseup', stopResizing, false);
}
function startResizing(e) {  
    // Do resize here
}
function stopResizing(e) {  
    window.removeEventListener('mousemove', startResizing, false);
    window.removeEventListener('mouseup', stopResizing, false);
}

To resize the box according to the user’s mouse pointer movements, we’ll be taking the current x and y coordinates of the mouse pointer (in pixels) and change the box’s height and width accordingly.

function startResizing(e) {  
   box.style.width = (e.clientX) + 'px';
   box.style.height = (e.clientY) + 'px';
}

e.clientX gives the mouse pointer’s X coordinate and e.clientY gives the mouse pointer’s Y coordinate

Now, this works. But this would only work as expected if the box is placed in the top-left corner of the page. We’ll have to compensate for the box’s left and top offsets. (position from the left and top edges of the page)

function startResizing(e) {  
   box.style.width = (e.clientX - box.offsetLeft) + 'px';
   box.style.height = (e.clientY - box.offsetTop) + 'px';
}

There you go :smile: We can now resize the box !

https://jsfiddle.net/niranjan94/w8k1ffju/embedded

Continue ReadingBuilding interactive elements with HTML and javascript: Resizing

Paginated APIs in Flask

Week 2 of GSoC I had the task of implementing paginated APIs in Open Event project. I was aware that DRF provided such feature in Django so I looked through the Internet to find some library for Flask. Luckily, I didn’t find any so I decided to make my own.

A paginated API is page-based API. This approach is used as the API data can be very large sometimes and pagination can help to break it into small chunks. The Paginated API built in the Open Event project looks like this –

{
    "start": 41,
    "limit": 20,
    "count": 128,
    "next": "/api/v2/events/page?start=61&limit=20",
    "previous": "/api/v2/events/page?start=21&limit=20",
    "results": [
    	{
    		"data": "data"
    	},
    	{
    		"data": "data"
    	}
    ]
}

Let me explain what the keys in this JSON mean –

  1. start – It is the position from which we want the data to be returned.
  2. limit – It is the max number of items to return from that position.
  3. next – It is the url for the next page of the query assuming current value of limit
  4. previous – It is the url for the previous page of the query assuming current value of limit
  5. count – It is the total count of results available in the dataset. Here as the ‘count’ is 128, that means you can go maximum till start=121 keeping limit as 20. Also when you get the page with start=121 and limit=20, 8 items will be returned.
  6. results – This is the list of results whose position lies within the bounds specified by the request.

Now let’s see how to implement it. I have simplified the code to make it easier to understand.

from flask import Flask, abort, request, jsonify
from models import Event

app = Flask(__name__)

@app.route('/api/v2/events/page')
def view():
	return jsonify(get_paginated_list(
		Event, 
		'/api/v2/events/page', 
		start=request.args.get('start', 1), 
		limit=request.args.get('limit', 20)
	))

def get_paginated_list(klass, url, start, limit):
    # check if page exists
    results = klass.query.all()
    count = len(results)
    if (count < start):
        abort(404)
    # make response
    obj = {}
    obj['start'] = start
    obj['limit'] = limit
    obj['count'] = count
    # make URLs
    # make previous url
    if start == 1:
        obj['previous'] = ''
    else:
        start_copy = max(1, start - limit)
        limit_copy = start - 1
        obj['previous'] = url + '?start=%d&limit=%d' % (start_copy, limit_copy)
    # make next url
    if start + limit > count:
        obj['next'] = ''
    else:
        start_copy = start + limit
        obj['next'] = url + '?start=%d&limit=%d' % (start_copy, limit)
    # finally extract result according to bounds
    obj['results'] = results[(start - 1):(start - 1 + limit)]
    return obj

Just to be clear, here I am assuming you are using SQLAlchemy for the database. The klass parameter in the above code is the SqlAlchemy db.Model class on which you want to query upon for the results. The url is the base url of the request, here ‘/api/v2/events/page’ and it used in setting the previous and next urls. Other things should be clear from the code.

So this was how to implement your very own Paginated API framework in Flask (should say Python). I hope you found this post interesting.

Until next time.

Ciao

 

{{ Repost from my personal blog http://aviaryan.in/blog/gsoc/paginated-apis-flask.html }}

Continue ReadingPaginated APIs in Flask

Getting Signed Release apk’s from the command line

 

View at Medium.com

If anyone of you has deployed an application on the play store, you may have most probably used Android Studio’s built in Generate signed apkoption.

The generate apk option in android studio

Recently while making the Open Event Apk generator, I had to make release apk’s, so that they could be used by an event organiser to publish their app, plus apk’s had to be signed because if they were not signed, it would be impossible to upload due to checks by Google.

Error shown on the developers console

So since I was building the app using the terminal and I didn’t have the luxury of signing the app using Android studio and I had to look for alternatives. Luckily I found two of them :

  1. Using the Signing configs offered by gradle
  2. Using the Oracle sun jarsigner

First of all the signing configs in gradle is a great way to do this. Most Open source apps use this as a way to put their code out for everyone to view and sucessfully hide any private keys and password.

You just need to add few lines of code in your app level build.gradle file and create a file called keystore.properties

In your keystore.properties, we just need to store the sensitive info and this file will be accessible only to people who are part of the project.

storePassword=myStorePassword
keyPassword=mykeyPassword
keyAlias=myKeyAlias
storeFile=myStoreFileLocation

Next we go to the build.gradle and add these lines to read the keystore.properties file and it’s variables

// Create a variable called keystorePropertiesFile, and initialize it to your
// keystore.properties file, in the rootProject folder.
def keystorePropertiesFile = rootProject.file("keystore.properties")

// Initialize a new Properties() object called keystoreProperties.
def keystoreProperties = new Properties()

// Load your keystore.properties file into the keystoreProperties object.
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))

Next we can add the signingConfigs task and reference the values we got above over there

android {
    signingConfigs {
        config {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']
        }
    }
    ...
  }

So As you see this is as simple as this but according to my requirements this seemed a bit tedious since a person setting up the apk generator had to make a keystore file, then find the build.gradle and change the path of the keystore file according to the server directories. So this does the trick but this can be so tedious for someone with no technical experience, so I researched on other solutions and then I got it : Jarsigner and Zipalign

First of all,the jarsigner and zipalign are 2 great tools and the best part about them is that both of them work perfectly with a just one line commands. For signing the app :

jarsigner -keystore <keystore_file> -storepass <storepassword> <apknameTosigned> <alias>

and then zipaligning :

zipalign -v 4 <unaligned-apk-location> <path-to-generated-aligned-apk>

So this is it, we finally used these 2 commands to sign and zipalign an apk and it works perfectly fine. Please test and share comments of the demo live @ http://192.241.232.231. Ciao !

Continue ReadingGetting Signed Release apk’s from the command line

Working with Absolute Positioning

During the past week, I have done a lot of work for making the feature that allow the users to view the schedule of events according to track and time. The toughest part was to have a headstart to think of the mockup that fulfills this criterion.

After the mockup, I started coding it and realized that I have to add CSS by using Javascript. The frontend needs to calculate the top of each pop-up that appears when the track is hovered and to append the box just below it.

a

The interesting part was to calculate the top each time the element is hovered and to place the box at the right position by using jQuery.

Position Absolute 

The difficulty becomes maximum when we use “position : absolute “. As, it takes the element out of the layer. The element with absolute positioning is difficult to handle when it comes to responsiveness. Here also the pop-overs showing the speakers are to be made with absolute positioning.

The code snippet shows the calculation for exact position of the pop-up box.

$(document).ready(function(){

 $('.pop-box').hide();
 $('.item').hover(function (event) {

 event.preventDefault();
 event.stopPropagation();
 var track = $(event.target);
 var link = track.children(0);
 var offset =$(link).offset();

 var position= offset.top-link.height()-30;
 if( $(window).width()<600){
 var position= offset.top-link.height()-48; 
 }
 if(offset.top){
 
 $('.pop-box').hide();
 var p=$(this);
 $(p).next().show();
 var posY = event.pageY;
 nextOfpop=$(p).next();
 
 var toptrack = position ;

 $(nextOfpop).css({'top':toptrack
                 });

 $(document).mouseup(function (e)
 {
 var container = $(".pop-box");

  if (!container.is(e.target) 
  && container.has(e.target).length === 0 && (e.target)!=$('html').get(0)) 
   {
   container.hide();
   }
   });
  });
 })

This code sets the value of top of the pop-over in the variable position and copy it to toptrack that is passed to CSS to adjust the top dynamically.

Responsiveness for top

I was struggling a whole day to find out the best possible way for the responsiveness of track page. Obviously, the difficult part was the recalculation of top with the screen-size. Currently I have used $window.width() to check the width of screen and adjust the top on mobile. But, it will include more complexity when it is done for other screen sizes rather than mobile.

 if( $(window).width()<600){
 var position= offset.top-link.height()-48; 
 }

The tracks page is ready now with both light and dark theme.

10.png

That’s how the position absolute is handled with jQuery. To remove the complexity, all the CSS except the calculation of top is written with SASS.

Continue ReadingWorking with Absolute Positioning

Migrations make us crazy!

Our Open Event team is not small, so problems with migrations occur very often. I’d like to describe how to solve these common problems and avoid Contributors frustration. Because more of us didn’t know how to solve this problems at the beginning so we wasted a lot of time to find a source of problem.

The most common mistake is that we forget run migration on Heroku. Developer is sometimes surprised because something works for him but he forgets to run migration on server. These small mistakes lead to huge problems and at that time our app throws a lots of bugs related to database. We can often see “Internal server error”.Screen Shot 2016-06-17 at 22.55.25.png So if developer changes table he has to run migration!

vagrant@vagrant-ubuntu-trusty-64:/vagrant$ python manage.py db migrate

But above command Quite often doesn’t solve our problem, because We face other problems while updating DB for example

alembic.util.exc.CommandError: Multiple head revisions are present for given argument ‘head’; please specify a specific target revision, ‘<branchname>@head’ to narrow to a specific head, or ‘heads’ for all heads

this problem is caused by two developers which push code to Github with migrations without merging two heads to achieve one head.

So to solve this problem you only have to know ids of two heads

vagrant@vagrant-ubuntu-trusty-64:/vagrant$ python manage.py db heads

e38935822969 (head)
f55fde3d62b1 (head)

Then you have to merge it

vagrant@vagrant-ubuntu-trusty-64:/vagrant$ python manage.py db merge e38935822969 f55fde3d62b1

Generating /vagrant/migrations/versions/ecb671d1eb4b_.py … done

Upgrade DB

vagrant@vagrant-ubuntu-trusty-64:/vagrant$ python manage.py db upgrade

INFO [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL.
INFO [alembic.runtime.migration] Running upgrade 00ea66754d06 -> d84f976530e1, empty message
INFO [alembic.runtime.migration] Running upgrade d84f976530e1 -> 1b3e4f5f56bd, empty message
INFO [alembic.runtime.migration] Running upgrade 1b3e4f5f56bd -> e38935822969, empty message
INFO [alembic.runtime.migration] Running upgrade e38935822969, f55fde3d62b1 -> ecb671d1eb4b, empty message

And finally run migrations

vagrant@vagrant-ubuntu-trusty-64:/vagrant$ python manage.py db migrate
INFO [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL.
INFO [alembic.ddl.postgresql] Detected sequence named ‘role_id_seq’ as owned by integer column ‘role(id)’, assuming SERIAL and omitting
INFO [alembic.ddl.postgresql] Detected sequence named ‘microlocation_id_seq’ as owned by integer column ‘microlocation(id)’, assuming SERIAL and omitting….

Continue ReadingMigrations make us crazy!

File Uploading in Flask

Last week I took up an issue of adding upload functionality to the open-event server. I had to implement the upload in 3 places – one in the sponsor table to upload images, another in the user profile page and the third is to upload slides in the session form. However the basic function behind it remains the same. File upload makes use of the inbuilt werkzeug FileStorage class. A code snippet will help understand how it works:

Capture.PNG

So  on selecting the file it gets stored in the request.files object. It is temporarily stored in the FileStorage in werkzeug. Now we access the file’s name using request.files[‘files’] and then using the inbuilt save()  function in flask it gets saved to the folder specified by us. There are some frameworks available for file uploading in Flask but all this can be done using the standard libraries also and there is no such need of the frameworks.

However instead of storing just the direct name of the file we make use of the secure_filename of werkzeug to save it.Capture2.PNG

Thus the secure_filename stores the file in the format given in the image and makes uploading easier by converting the long url/image path to an easier one.

Continue ReadingFile Uploading in Flask

Open Event Organizer’s Server: Custom Forms

As we know, open event organizer’s server provides a means of creating events. And an important part of events is sessions and speakers of sessions. But different events have different details required for sessions and speakers of sessions. Some might feel that only Name and Email-ID of speaker is enough, while others may require their Github, Facebook, etc. links. So the best way to solve this is to make a custom form so that the organizers get to select what all fields they want in the forms. But how to do this? Well, thanks to JSON

In the Step-5 of Event Creation Wizards, we have option (or switches) to include and require various fields available for the session form and speaker form for applying in a particular Session Form. Here is how it looks:
custom_form.png

As we can see, each field has 2 options – Include and Require. On clicking the Include switch the Require switch is enabled through jQuery. The Include switch means that the field is included in the form while the Require switch signifies that the field will be a compulsory field in the form.

Storing Options

We create a javascript array containing a single object. This object in turn is made up of objects with field names as keys and another object as value. This object in turn contains the keys include and require. The value of include and require is 0 by default. On selecting, their value is changed to 1. An example structure of the array is like:

[{
    "title": {
        "include": 1,
        "require": 1
    },
    "subtitle": {
        "include": 0,
        "require": 0
    },
    "short_abstract": {
        "include": 1,
        "require": 0
    },
    "long_abstract": {
        "include": 0,
        "require": 0
    },
    "comments": {
        "include": 1,
        "require": 0
    },
    "track": {
        "include": 0,
        "require": 0
    },
    "session_type": {
        "include": 0,
        "require": 0
    },
    "language": {
        "include": 0,
        "require": 0
    },
    "slides": {
        "include": 1,
        "require": 0
    },
    "video": {
        "include": 0,
        "require": 0
    },
    "audio": {
        "include": 0,
        "require": 0
    }
}]

This array is then converted to string format using JSON.stringify, submitted through form and stored in database in the form of a string.

Rendering Forms

Now, we have already stored the options as selected by the organizer. But now we need to render the forms based on the JSON string stored in the database. Firstly, in the server side we convert the string to JSON object in python using json.loads . Then we send these JSON objects to the templates.

In the templates, we create form elements based on the values of the include and require of each form element. A sample element HTML is like this:

Screenshot from 2016-06-17 22:38:40

We use a loop to iterate over the JSON object and thus add the elements which have  “include = 1”  . The final form looks something like this:

session-form

Continue ReadingOpen Event Organizer’s Server: Custom Forms

Sending e-mail from linux terminal

So while finalizing the apk-generator for my GSoC project, I faced a roadblock in sending the generated App to the organizer.

Normally the build takes around 10–12 minutes, so asking the user to wait for that long on the website and then providing him/her with a download link did not feel like a good option. (amirite?)

So I and Manan Wason thought of a different approach to this problem, which was to email the generated app to the organzier.

For doing this, we used 2 handy tools MSMTP and Mutt.
We can use MSMTP to send email but unfortunately we cannot include attachments, so we used Mutt to help us send email with attachments from the command line.
So hang tight and follow the rest of the guide to start sending emails from your terminal and get yourself some developer #swag

Step 1 : Installation

Use the following commands to install MSMTP and Mutt

sudo apt-get -y install msmtp
sudo apt-get -y install ca-certificates
sudo apt-get -y install mutt

We need to have a file that contains Certificate Authority (CA) certificates so that we can connect using SSL / TLS to the email server.

Step 2 : Configuring MSMTP

Now we’ll MSMTP configuration on /etc/msmtprc with the content below. NOTE : You will have to enter your username and password on this file so make sure to make this file private.

Lets first open this file

nano /etc/msmtprc

Next, add following text to the file,

account default
tls on
tls_starttls off
tls_certcheck off
auth on
host smtp.mail.yahoo.com (change this to smtp.gmail.com for gmail)
user username
password password
from username@yahoo.com
logfile /var/log/msmtp.log

NOTE : Refrain from using gmail as they might terminate your account for sending email via MSMTP.

For configuring mutt, we’ll use a similar command to edit the file located at /root/.muttrc

nano /root/.muttrc

Add following text to it which specifies the MSMTP account to use for sending email

set sendmail=”/usr/bin/msmtp”
set use_from=yes
set realname=”MY Real Name”
set from=username@yahoo.com
set envelope_from=yes

That’s it!
Now lets get ready for the fun part, SENDING THOSE EMAILS 😀

Step 3 : Sending

Now, there are 2 cases that might arise while sending the email,

1 : Sending without attachment

This is pretty straightforward and can be done with either MSMTP or Mutt.

Using MSMTP

printf “To: recipient@domain.comnFrom: username@domain.comnSubject: Testing MSMTPnnHello there. This is email test from MSMTP.” | msmtp recipient@domain.com

Entering the following code will send the email to the recipient and also display the sent email in the terminal.

Using Mutt

mutt -s “Testing Mutt” — recipient@domain.com < /path/to/body.txt

NOTE : ‘body.txt’ is the file whose contents will be used in the body of the email that will be sent to ‘recipient@domain.com’.

2 : Sending WITH an attachment

Unlike the previous case, this can be done ONLY using Mutt and the code used is

mutt -a /path/to/attachment.txt -s “Testing Mutt — recipient@domain.com < /path/to/body.txt

The syntax is similar to the above case where we sent the email without attachments.

So well, that it then!
If you followed the instructions carefully, you will have a working email client built into your terminal!
Pretty cool right?

So that’s it for this week, hope to catch you next week with some more interesting tips and tutorials.

Continue ReadingSending e-mail from linux terminal

Errors and Error handlers for REST API

Errors are an essential part of a REST API system. Error instances must follow a particular structure so the client developer can correctly handle them at the client side. We had set a proper error structure at the beginning of creating REST APIs. It’s as follows:

{
    "error": {
        "message": "Error description",
        "code": 400
    }
}

Any error occurring during client server communication would follow the above format. Code is the returned status code and message is a brief description of the error. To raise an error we used an _error_abort() function which was an abstraction over Flask-RESTplus abort(). We defined an error structure inside _error_abort() and passed it to abort().

def _error_abort(code, message):
    error = {
        'code': code,
        'message': message,
    }
    abort(code, error=error)

This method had its limitations. Since the error handlers were not being overidden, only errors raised through _error_abort() had the defined structure. So if an Internal Server error occurred, the returned error response wouldn’t follow the format.

To overcome this, we wrote our own exceptions for errors and created error handlers to handle them. We first made the response structure more detailed, so the client developer can understand what kind of error is being returned.

{
    "error": {
        "code": 400,
        "message": "'name' is a required parameter",
        "status": "INVALID_FIELD",
        "field": "name"
    }
}

The above is an example of a validation error.

The “status” key helps making the error more unique. For example we use 400 status code for both validation errors and invalid service errors (“Service not belonging to said event”). But both have different statuses: “INVALID_FIELD” and “INVALID_SERVICE”.

The “field” key is only useful in the case validation errors, where it names the field that did not pass the validation. For other errors it remains null.

I first documented what kind of errors we would need.

Code Status Field Description
401 NOT_AUTHORIZED null Invalid token or user not authenticated
400 INVALID_FIELD “field_name” Missing or invalid field
400 INVALID_SERVICE null Service ID mentioned in path does not belong to said Event
404 NOT_FOUND null Event or Service not found
403 PERMISSION_DENIED null User role not allowed to perform such action
500 SERVER_ERROR null Internal server error

Next part was creating exception classes for each one these. I created a base error class that extended the python Exception class.

class BaseError(Exception):
    """Base Error Class"""

    def __init__(self, code=400, message='', status='', field=None):
        Exception.__init__(self)
        self.code = code
        self.message = message
        self.status = status
        self.field = field

    def to_dict(self):
        return {'code': self.code,
                'message': self.message,
                'status': self.status,
                'field': self.field, }

The to_dict() method would help when returning the response in error handlers.

I then extended this base class to other error classes. Here are three of them:

class NotFoundError(BaseError):
    def __init__(self, message='Not found'):
        BaseError.__init__(self)
        self.code = 404
        self.message = message
        self.status = 'NOT_FOUND'


class NotAuthorizedError(BaseError):
    def __init__(self, message='Unauthorized'):
        BaseError.__init__(self)
        self.code = 401
        self.message = message
        self.status = 'NOT_AUTHORIZED'


class ValidationError(BaseError):
    def __init__(self, field, message='Invalid field'):
        BaseError.__init__(self)
        self.code = 400
        self.message = message
        self.status = 'INVALID_FIELD'
        self.field = field

I then defined the error handlers for the api:

@api.errorhandler(NotFoundError)
@api.errorhandler(NotAuthorizedError)
@api.errorhandler(ValidationError)
@api.errorhandler(InvalidServiceError)
def handle_error(error):
    return error.to_dict(), getattr(error, 'code')

For overriding the default error handler, Flask-RESTplus let’s you create one with the same decorator, but without passing and argument to it.

@api.errorhandler
def default_error_handler(error):
    """Returns Internal server error"""
    error = ServerError()
    return error.to_dict(), getattr(error, 'code', 500)

I had set the default error to be the internal server error.

class ServerError(BaseError):
    def __init__(self, message='Internal server error'):
        BaseError.__init__(self)
        self.code = 500
        self.message = message
        self.status = 'SERVER_ERROR'

Now raising any of these error classes would activate the error handlers and a proper response would be sent to the client.

Continue ReadingErrors and Error handlers for REST API