Пирамида легкий Python Веб-каркас после архитектурного шаблона MVC. В этой статье мы создадим веб-приложение и API с помощью пирамиды.
Pyramid – это подходящая рамка для крупных приложений MVC, и она поставляется с гибкими инструментами для загрузки.
Cornice, библиотека из Mozilla, позволяет легко разрабатывать спокойные веб-сервисы с пирамидой.
Установка
Сначала мы создаем виртуальную среду, которая помогает нам в разделении удельных Python Python Pathon Packages из других проектов. После активации виртуальной среды мы устанавливаем Pyramid Framework с помощью команды:
pip install pyramid
Создание моделей
Мы создаем Models.py
Файл с классом Примечание, на котором отображается таблица данных, хранящая все значения примечаний.
# 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
Взгляды
В Просмотр .py
Файл, мы добавляем наши услуги для разных запросов API.
@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) ] }
Запуск приложения
Создайте схему базы данных путем выполнения:
python initialize_db.py
Запустите сервер разработки по:
python setup.py develop pserve note.ini --reload
Мы можем просмотреть заметки, навигацию на URL http://localhost: 6543/Примечания в браузере.
Откройте оболочку Python и выполните запросы на 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')
Исходный код можно найти на гадость
Надеюсь, что статья была помощи!
Статья первоначально появилась на Apcelent Tech Blog Отказ
Оригинал: “https://dev.to/apcelent/how-to-create-rest-api-using-pyramid-m52”