Pyramid is a lightweight python web framework following MVC architectural pattern. In this article, we will set up a web application and API using Pyramid.
Pyramid is a suitable framework for large scale MVC applications and it comes with flexible bootstrapping tools.
Cornice, a library from Mozilla, makes it easy to develop RESTful web services with pyramid.
Installation
First we create a virtual environment which helps us in separating project specific python packages installations from other projects. After activating the virtual environment, we install pyramid framework using command:
pip install pyramid
Create models
We create a models.py file with a class Note which maps to the data table storing all the values of notes.
# pyramidapp/models.py
class Note(Base):
    __tablename__ = 'Note'
    id = Column(Integer, primary_key=True)
    title = Column(Text)
    description = Column(Text)
    create_at = Column(Text)
    create_by = Column(Text)
    priority = Column(Integer)
    def __init__(self, title, description, create_at ,create_by, priority):
        self.title = title
        self.description = description
        self.create_at = create_at
        self.create_by = create_by
        self.priority = priority
    @classmethod
    def from_json(cls, data):
        return cls(**data)
    def to_json(self):
        to_serialize = ['id', 'title', 'description', 'create_at', 'create_by', 'priority']
        d = {}
        for attr_name in to_serialize:
            d[attr_name] = getattr(self, attr_name)
        return d
Views
In views.py file, we add our services for different API requests.
@resource(collection_path='/notes', path='/notes/{id}')
class NoteView(object):
    def __init__(self, request):
        self.request = request
    def collection_get(self):
        return {
            'notes': [
                {'id': note.id, 'title': note.title, 'description': note.description,
                'create_at': note.create_at, 'create_by': note.create_by, 'priority': note.priority}
                    for note in DBSession.query(Note)
                    ]
            }
    def get(self):
        try:
            return DBSession.query(Note).get(
                int(self.request.matchdict['id'])).to_json()
        except:
            return {}
    def collection_post(self):
        note = self.request.json
        DBSession.add(Note.from_json(note))
    def put(self):
        try:
            obj=DBSession.query(Note).filter(Note.id==self.request.matchdict['id'])
            obj.update(self.request.json)
            return {'notes': [
                    {'id': note.id, 'title': note.title, 'description': note.description,
                    'create_at': note.create_at, 'create_by': note.create_by, 'priority': note.priority}
                        for note in DBSession.query(Note)
                        ]
                    }
        except:
            return {'result': 'No object found'}
    def delete(self):
        obj=DBSession.query(Note).filter(Note.id==self.request.matchdict['id']).first()
        DBSession.delete(obj)
        return {'notes': [
                {'id': note.id, 'title': note.title, 'description': note.description,
                'create_at': note.create_at, 'create_by': note.create_by, 'priority': note.priority}
                    for note in DBSession.query(Note)
                    ]
                }
Running the application
Create the database schema by executing:
python initialize_db.py
Start the development server by:
python setup.py develop
pserve note.ini --reload
We can view the notes by navigating to the URL http://localhost:6543/notes in browser.
Open python shell and execute requests for API:
requests.post('http://localhost:6543/notes',
                 headers={'Content-Type': 'application/json'},
                data=json.dumps({   "title": "sample note one ",
                                    "create_at": "2017-08-23 00:00",
                                    "create_by": "apcelent",
                                    "description": "sample notes",
                                    "priority": 3,
                                }))
requests.put('http://localhost:6543/notes/1',
                 headers={'Content-Type': 'application/json'},
                data=json.dumps({   "title": "sample note edit ",
                                    "create_at": "2017-08-23 00:00",
                                    "create_by": "apcelent",
                                    "description": "sample notes edit",
                                    "priority": 4,
                                }))
requests.delete('http://localhost:6543/notes/1')
The source code can be found on github
Hope the article was of help!
The article originally appeared on Apcelent Tech Blog.
 


 
    
Top comments (0)