Django REST Framework + Django REST Swagger - python

Having a hard time configuring Swagger UI Here are the very explanatory docs in - https://django-rest-swagger.readthedocs.io/en/latest/. My settings.py looks like this.
urls.py looks like this.
But the swagger web page isn't loading properly.
and the console log is as follows.
What might be the problem here?

Take a look at django-rest-swagger schema documentation, there is some code examples there about how this ties into DRF. You can read some more about this by visiting the DRF Schema Generator documentation.
If you just want to get up and running without learning more about the library, this article does a good job about showing project architecture and integrating DRS with DRF.

very first, install django rest framework into your application and import that in setting.py file
make few APIs using DRF and then add swagger setting inside your setting.py file
SWAGGER_SETTINGS = {
'SECURITY_DEFINITIONS': {
'api_key': {
'type': 'apiKey',
'in': 'header',
'name': 'Authorization'
}
}, # setting to pass token in header
'USE_SESSION_AUTH': False,
# set to True if session based authentication needed
'JSON_EDITOR': True,
'api_path': 'api/',
'api_version': 'v0',
"is_authenticated": False, # Set to True to enforce user authentication,
"is_superuser": False, # Set to True to enforce admin only access
'unauthenticated_user': 'django.contrib.auth.models.AnonymousUser',
# unauthenticated user will be shown as Anonymous user in swagger UI.
}
Note:- You can edit the swagger setting according to you need.

Related

Disable pagination inspector on drf_yasg

I'm using drf_yasg to create my swagger document but I have an issue with PaginationInspector. In one of my views I declare a paginator and in swagger, is shown as the default pagination for swagger.
Something like this:
count* integer #This info is generated automatically by swagger
next string($uri) #This info is generated automatically by swagger
x-nullable: true #This info is generated automatically by swagger
previous: string($uri) #This info is generated automatically by swagger
x-nullable: trueç
results: (THE BODY I ACTUALLY WANT TO SHOW)
I would like that the swagger ignore that pagination but haven’t found any info related to it.
I try using the decorator, initially I though it could be something like #swagger_auto_schema(paginator_inspectors=False) but it doesn't work and I can't find anything useful on the docs. Thanks in advance
oh and just in case this is my view:
class CharacterView(ListChView):
class OutputSerializer(serializers.Serializer):
id = serializers.CharField(source="external_id")
created_at = serializers.DateTimeField()
pagination_class = CustomPagination
Just override get_paginated_response_schema method.
class CustomPagination(PageNumberPagination):
...
# add
def get_paginated_response_schema(self, schema):
return {
'type': 'object',
'properties': {
'results': schema,
},
}

Implementing Vue RESTful API calls in Django within Django Templates with Session Authentication

I have a Django project that requires page refreshes any time I want to update the content. Currently it uses the built in Django Class Based Views, which in turn use Templates.
I want to start implementing some javascript calls to refresh tables/forms/modal windows with new data, mostly in response to button clicks. I'm trying to use Vue to accomplish this, and I have created a Django REST Framework backend to facilitate this.
I got a simple 'Hello world' vue class working where the data is hard coded into the data field of the Vue class. I can't seem to make the jump to getting data from the API though. I am getting an Unauthorized response. I am using vue-resource for the HTTP API call.
I have unit tests where I call the API from the DRF APITestCase using the self.client.get('api/path') and they work as expected (unauthorized when there is no authenticated user attached to request, authorized when there is).
I have debugged into the DRF Permission class to see why the request is being refused and it is because there is no authenticated User attached to the request.
I have added SessionAuthentication to the DEFAULT_AUTHENTICATION_CLASSES in settings.
My question is, how do I add an authenticated user to the request so that when the Vue method is called from within my webapp the API request will be authorized?
I'm not sure if this is complicating matters but I am using a custom user model within Django for authentication.
I am hoping to start off by implementing a few Vue controls throughout my website, for instance the tables and forms mentioned. I don't want to turn this into a single page app. I would like to continue using the Django views for user authentication.
My Vue code looks like so;
new Vue({
delimiters: ['${', '}$'],
el: '.events-table',
data: {
message: 'Hello Vue!',
demo: [
{ id: 5 },
{ id: 2 },
{ id: 3 },
],
events: [],
},
http: {
root: 'http://localhost:8000',
},
methods: {
getEvents: function () {
this.$http.get('api/eventlog/events/?format=json').then(
function (data, status, request) {
if (status == 200) {
this.events = data.body.results;
}
}
)
}
},
mounted: function () {
this.getEvents();
}
})
I changed the http property like so
http: {
root: window.location.origin,
},
and now it seems to recognise that the request is coming from an authenticated session.

How can I enforce Basic Auth in Flask Restplus Swagger UI?

I am developing a back-end and using Flask Restplus. So far the code works great and the Swagger UI looks great too. I am considering adding Basic Auth on a particular endpoint (I am planning on using a Basic Auth Decorator from a previous Flask-Restful project).
How can I make the username and password fields visible on the swagger UI as well as actually enforce it on the UI? I was poking around the restplus documentation as well as Stack Overflow and didn't really see anything.
The UI will be visible on an intranet/LAN... I don't want this endpoint to be available to everyone in the building.
Implement below:
authorizations = {
'Basic Auth': {
'type': 'basic',
'in': 'header',
'name': 'Authorization'
},
}
api = Namespace('User', description='user related operations',security='Bearer Auth', authorizations=authorizations)

Django-Allauth Facebook integration - Ask for permission to post to User's wall separately

I am using django-allauth in my Django application.
Every user has an option to connect his/her Facebook account to their existing account.
I was able to to do this by adding allauth's connect process.
<a href='{% provider_login_url "facebook" process="connect" %}'>
Connect with Facebook
</a>
At this point, I don't want to ask for permission to post to the user's wall.
#settings.py
SOCIALACCOUNT_PROVIDERS = {
'facebook': {
'SCOPE': ['email'],
'METHOD': 'js_sdk'
}
}
All goes well and the user can connect a Facebook account.
But, is there a way to ask for permission to post on the user's wall separately? I don't want to ask for publish_actions permissions above.
How do I do this using django-allauth?
How do I ask for publish_actions permission separately? Can this be done using django-allauth? Because I am guessing this requires re-declaring 'SCOPE' for 'facebook' SOCIALACCOUNT_PROVIDERS in settings.py.
Thanks in advance
I finally solved it. Turns out that django allauth saves the settings as JSON in the DOM element #allauth-facebook-settings. You just have to modify this json and pass to the allauth facebook init function. When the user clicks to enable a feature which requires 'publish_actions' permission, I call a Javascript function:
function modify_permissions() {
var json = JSON.parse($("#allauth-facebook-settings").html());
json["loginOptions"]["scope"] = "email, publish_actions";
allauth.facebook.init(json);
}
Now, if you try to connect a FB account from that page, django allauth will ask for 'publish_actions' permission too.
In the SOCIALACCOUNT_PROVIDER setting provided by django allauth http://django-allauth.readthedocs.io/en/latest/providers.html#facebook You would need to change the following section to include any extra permission you need
SOCIALACCOUNT_PROVIDERS = {
'facebook': {
'SCOPE': ['email', 'public_profile', 'publish_actions'], # add your permissions here
'METHOD': 'js_sdk',
...
}
}

Authenticating users using pusher in django

I am a bit confused on how does the Authentication works in Django using pusher i want to implement a one-to-one chatting system so i guess i will be using private channels that requires authentication before you can subscribe to the channel ... i read there that the endpoint is the url you want pusher to POST to, i added a url to test if it is working but every time the status returns 403 and it seems it doesn't enter the view i created to test it so any ideas ? here is a sample of my code :
message.html
var channel = pusher.subscribe('private-test');
channel.bind('message', function(data) {
var $message = $('<div class="message"/>').appendTo('#messages');
$('<span class="user"/>').text(data.user).appendTo($message);
$('<span/>').text(data.message).appendTo($message);
});;
Pusher.channel_auth_endpoint = 'test/';
Pusher.channel_auth_transport = 'ajax';
channel.bind('pusher:subscription_succeeded', function(status) {
alert(status);
});
channel.bind('pusher:subscription_error', function(status) {
alert(status);
});
Views.py:
def testUser(request,user_name):
print 'Test Passed'
return render_to_response('message.html', {
'PUSHER_KEY': settings.PUSHER_KEY,'channel_variable':request.user.id,'other_var':'3',
}, RequestContext(request))
when i checked the url it POSTs to, in my cmd i found it correct and it matched the one i put in urls.py but i still don't know why it does not enter my view
I don't know Django, but it seems highly likely that the framework is intercepting the call to prevent CSRF (Cross site resource forgery).
The Django docs talk about CSRF here:
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
As with a number of frameworks you'll need to provide a CSRF token as part of the XHR/AJAX call to the authentication endpoint, or override the framework interception (somehow).
Have a look at the auth section of the Pusher constructor options parameter. In there you'll find an example of how to pass a CSRF token.

Categories