I have RESTFul API written in pyramid. View functions processes data in request.POST and request.matchdict and returns json response.
Eg: A method inside view class.
#view_config(route_name="temp_name", request_method="PUT")
def put_item(self):
# validates and processes self.request.POST
# validates and processes self.request.matchdict
# returns json reponse
As you can see, I'm doing validation inside view method, which I want to avoid.My intention is to separate validation from actual functionality.
How do I handle this?
I saw colander http://cornice.readthedocs.org/en/latest/validation.html#using-colander which looks really good in my case. But looks like it is integrated with cornice which I'm not using at all. And also, I can't convert whole app into cornice now. Is it possible to use colander in the same way as given in the above link with my app?
This is the first time I'm writing RESTFul API's, also just started learning pyramid and colander. Need your help. Thanks in advance.
You can use Colander independently of cornice. The most basic example for using Colander Schema in a pyramid application I remember you find here:
http://docs.pylonsproject.org/projects/pyramid_tutorials/en/latest/humans/zodb/index.html
This way you can encapsulate schema validation using colander schemas and validators.
A more recent introduction of pyramid 1.5 branch into that topic you find here:
http://pyramid.readthedocs.org/en/1.5-branch/quick_tutorial/forms.html
Oh, and look at that SO question. I liked it, may be it will be helpful to you as well:
Which one is the correct approach for form validation ? Colander's Schema validation or Deform's form validation?
Related
I am a php programmer, I have built some REST based solutions in php. Now I am learning python/django. I want to make a REST based solution in Django ( only for knowledge purpose ). I do not want to use any of REST frameworks/toolkits as This project is more a exploring django/python say how they work with raw REST concept.
I searched on net, But examples/tutorial filled on already built solutions. I also checkout for request method based filtering. I am thinking of two approaches.
Either urls.py have way to check request method and transfer to respective method in views.py.
Or I can add a pre load hook/class which determine request method on application initialize, And called respective method so overriding urls.py behavior (my preferred method).
If anybody can suggest a django way to do this?
Update : I found some interesting comments on SO, like https://stackoverflow.com/a/20898410/1230744 AND https://stackoverflow.com/a/1732520/1230744. Need to check if they can have the solution, I am searching.
Well I get the answer of my questions finally from following link. It is possible through using Class based Views + serialization.
Restful routes and Django
Snippet links in side above link gave pretty much example to gave quite picture of how one can create a REST Api using only Django Core. Also I used serialize https://docs.djangoproject.com/en/dev/topics/serialization/ for Json encoding
( Now if anybody prefer, he can flag duplicate the question. ;) )
You can start from learning the code of this projects:
http://tastypieapi.org/ Tastypie
http://www.django-rest-framework.org/ Django REST framework
They are snadrd de facto for REST API for Django and their code could be a good starting point.
Also, please review this questions:
Creating a REST API for a Django application
Adding REST to Django
Django and Restful APIs
I have created a number of Django-tastypie resource definitions in resources.py. Most of them will be created by posting from javascript side (backbone-tastypie), but some of them I would like to be able to create right from python code/django views.
The reason for this is that object creation logic should be kept in one place, as well as authorization params.
Is there some neat way to create TastyPie ModelResource inside Python code? (may be making a "post" with "Requests" module?).
If i understand you right, your usecase is described in tastypie cookbook: http://django-tastypie.readthedocs.org/en/latest/cookbook.html#using-your-resource-in-regular-views
We would like to have a OData JSON interface on our Django (Python 2.5.4) website. At the moment of writing there seems to be no library available.
I'm thinking of writing "some" logic to handle this ourselves.
Would it be a good idea to extend the Django JSON serializer?
Where and how to store the URI's related to the models?
I think it would be a good idea to extend the Django JSON serializer, but have a look at django-piston this might be the better route to go.
The URI's will have to be defined in your urls.py for your app, and then in your models you could define a function
get_odata_uri()
Which would work like the Django's get_absolute_url(). Instead of hardcoding it into your model, make sure you make use of the reverse function from django.core.urlresolvers
I am adding MetaWeblog API support to a Django CMS, and am not quite sure how to layer the application.
I am using django_xmlrpc, which allows me to map to parameterised functions for each request. It is just a case of what level do I hook in calls to the django application from the service functions (AddPage, EditPage etc)
For django-page-cms, and I suppose many django apps, the business logic and validation is contained within the forms. In this case there is PageForm(forms.ModelForm) and PageAdmin(ModelAdmin), which both contain a lot of logic and validation.
If I am to build an API to allow maintenance of pages and content, does this mean I should be programmatically creating and filling a PageAdmin instance? Then catching any exceptions, and converting to their api equivalent? Or would this be a bad idea - misusing what forms are intended for?
The other option is refactoring the code so that business and logic is kept outside of the form classes. Then I would have the form and api, both go through the separate business logic.
Any other alternatives?
What would be the best solution?
Web services API's are just more URL's.
These WS API URL's map to view functions.
The WS view functions handle GET and POST (and possibly PUT and DELETE).
The WS view functions use Forms as well as the Models to make things happen.
It is, in a way, like an admin interface. Except, there's no HTML.
The WS view functions respond with JSON messages or XML messages.
It seems python does not provide this out of the box. But there is something called abc module:
I quote from http://www.doughellmann.com/PyMOTW/abc/ "By defining an abstract base class, you can define a common API for a set of subclasses. This capability is especially useful in situations where a third-party is going to provide implementations..." => the goal of an API, defining a contract.
Pretty new to this scene and trying to find some documentation to adopt best practices. We're building a fairly large content site which will consist of various media catalogs and I'm trying to find some comparable data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before. Any insight / help would be greatly appreciated!
"data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before"
Django imposes best practices on you. You don't have a lot of choices and can't make a lot of mistakes.
MVC (while a noble aspiration) is implemented as follows:
Data is defined in "models.py" files using the Django ORM models.
urls.py file maps URL to view function. Pick your URL's wisely.
View function does all processing, making use of models and methods in models
Presentation (via HTML templates) invoked by View function. Essentially no processing can be done in presentation, just lightweight iteration and decision-making
The model is defined for you. Just stick to what Django does naturally and you'll be happy.
Architecturally, you usually have a stack like this.
Apache does two things.
serves static content directly and immediately
hands dynamic URL to Django (via mod_python, mod_wsgi or mod_fastcgi). Django apps map URL to view functions (which access to database (via ORM/model) and display via templates.
Database used by Django view functions.
The architecture is well-defined for you. Just stick to what Django does naturally and you'll be happy.
Feel free to read the Django documentation. It's excellent; perhaps the best there is.
first, forget all MVC mantra. it's important to have a good layered structure, but MVC (as defined originally) isn't one, it was a modular structure, where each GUI module is split in these tree submodules. nothing to use on the web here.
in web development, it really pays to have a layered structure, where the most important layer is the storage/modelling one, which came to be called model layer. on top of that, you need a few other layers but they're really not anything like views and controllers in the GUI world.
the Django layers are roughly:
storage/modelling: models.py, obviously. try to put most of the 'working' concepts there. all the relationships, all the operations should be implemented here.
dispatching: mostly in urls.py. here you turn your URL scheme into code paths. think of it like a big switch() statement. try hard to have readable URLs, which map into user intentions. it will help a lot to add new functionality, or new ways to do the same things (like an AJAX UI later).
gathering: mostly the view functions, both yours and the prebuilt generic views. here you simply gather all the from the models to satisfy a user request. in surprisingly many cases, it just have to pick a single model instance, and everything else can be retrieved from relationships. for these URLs, a generic view is enough.
presentation: the templates. if the view gives you the data you need, it's simple enough to turn it into a webpage. it's here where you'll thank that the model classes have good accessors to get any kind of relevant data from any given instance.
To understand django fundementals and the django take on MVC, consult the following:
http://www.djangobook.com/
As a starting point to getting your hands dirty with ...
"...trying to find some comparable data / architectural models"
Here is a quick and dirty way to reverse engineer a database to get a models.py file,
which you can then inspect to see how django would handle it.
1.) get an er diagram that closely matches your target. For example something like this
http://www.databaseanswers.org/data_models/product_catalogs/index.htm
2.) create an sql script from the er diagram and create the database,
I suggest Postgre, as some MySQL
table type will not have forgien key constraints, but in a pinch MySQL or SQLITE
will do
3.) create and configure a django app to use that database. Then run:
python manage.py inspectdb
This will at least give you a models.py file which you can read to see how django attempts
to model it.
Note that the inspect command is intended to be a shortcut for dealing with legacy
database when developing in django, and as such is not perfect. Be sure to read the
following before attempting this:
http://docs.djangoproject.com/en/dev/ref/django-admin/#ref-django-admin