analitics

Pages

Thursday, August 1, 2019

Python 3.7.3 : Using the flask - part 005.

In the last tutorial, I used the flask-sqlalchemy python module.
Today I will show you how to use the flask_marshmallow python module.
First, let's take a look at this python module, see the official webpage:
Flask-Marshmallow is a thin integration layer for Flask (a Python web framework) and marshmallow (an object serialization/deserialization library) that adds additional features to marshmallow, including URL and Hyperlinks fields for HATEOAS-ready APIs. It also (optionally) integrates with Flask-SQLAlchemy.
The base class User will need to be integrated with this python module:
from flask import Flask
from flask import render_template
from forms import SignUpForm
from flask import request

from flask import jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
from forms import AddUser

app = Flask (__name__)
app.config['SECRET_KEY'] = 'abcdefg'
# set SQLAlchemy
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'server.sqlite')
db = SQLAlchemy(app)
ma = Marshmallow(app)
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email
    '''
    def __rep_(self):
        return '' % self.username
    '''
class UserSchema(ma.ModelSchema):
    class Meta:
        model = User
user_schema = UserSchema()
users_schema = UserSchema(many=True)

@app.route("/users/", methods=['GET'])
def users():
    users = User.query.all()
    #return users_schema.jsonify(users)
    all_users = users_schema.dump(users)
    return jsonify(all_users.data)

# the default name main
if __name__ == '__main__':
    app.run(debug=True)
Let's take a look at http://127.0.0.1:5000/users/ and see the result:
[
  {
    "email": "catafest@yahoo.com", 
    "id": 1, 
    "username": "catafest"
  }, 
  {
    "email": "test@test.com", 
    "id": 2, 
    "username": "user_test"
  }
]