django #swagger_auto_schema properties - django

I want to put this response in swagger doc too! I use drf_yasg app in django. I've written this code:
#swagger_auto_schema(method='post', request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
'login_id': openapi.Schema(type=openapi.TYPE_STRING, description='ID'),
'password': openapi.Schema(type=openapi.TYPE_STRING, description='password'),
}
))
The current swagger_auto_schema property is
{
"login_id": "admin",
"password": "1234",
}
I want to make swagger_auto_schema in the format below
{
"User": {
"login_id": "admin",
"password": "1234",
}
}
I don't know how to provide json data

You need to define the "User" wrapper explicitly in your schema:
#swagger_auto_schema(method='post', request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
'User': openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
'login_id': openapi.Schema(type=openapi.TYPE_STRING, description='ID'),
'password': openapi.Schema(type=openapi.TYPE_STRING, description='password'),
}
)
}
))

Related

stale token even for first time user Djoser and DRF

the newly registered user get email for activation . He clicks on the links and move to an activation page .then he clicks on verify button which take uid and token from the link and post it to auth/users/activation/ and then gets the response stale token for the given user no matter how fast he click on the link on verify link . result is same. I am using djoser for activation and all user related stuff.and redux in the frontend for api calls and also the React as frontend
here is my settings.py:
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(days=30),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'AUTH_HEADER_TYPES': ('JWT','Bearer'),
'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule' ,
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
}
DJOSER = {
'LOGIN_FIELD': 'email',
'USERNAME_CHANGED_EMAIL_CONFIRMATION': True,
'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True,
'SEND_CONFIRMATION_EMAIL': True,
'SET_USERNAME_RETYPE': True,
'SET_PASSWORD_RETYPE': True,
'PASSWORD_CHANGED_EMAIL_CONFIRMATION':True,
'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}',
'SEND_ACTIVATION_EMAIL': True,
'ACTIVATION_URL': 'activate/{uid}/{token}',
'SOCIAL_AUTH_TOKEN_STRATEGY': 'djoser.social.token.jwt.TokenStrategy',
'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': ['https://negoziohub.herokuapp.com/google', 'http://127.0.0.1:8000/facebook'],
'SERIALIZERS': {
'user_create': 'base.serializers.UserSerializer',
'user': 'base.serializers.UserSerializer',
'user_delete': 'djoser.serializers.UserDeleteSerializer',
}
}
here is userAction.js:
export const activate = (uid, token) => async (dispatch) => {
try {
dispatch({
type: USER_ACTIVATE_REQUEST
})
const config = {
headers: {
'Content-type': 'application/json',
}
}
const body = JSON.stringify({ uid, token });
const { data } = await axios.post(`/auth/users/activation/`, body,
config
)
dispatch({
type: USER_ACTIVATE_SUCCESS,
payload: data
})
// dispatch(login())
localStorage.setItem('userInfo', JSON.stringify(data))
} catch (error) {
dispatch({
type: USER_ACTIVATE_FAIL,
payload: error.response && error.response.data.detail
? error.response.data.detail
: error.message,
})
}
}
Any help would be appreciated. Thanks❤❤❤
I know it's too late to answer your question but I will do it just for other folks out there who might face the same issue in the future.
I had the same problem and I couldn't find anything on the internet, which drove me to dive deep in the source code of Djoser. The issue in my case was that I changed the default behavior to change the state of the user and set user.is_active = True. This was the issue as Djoser sends the stale token error if user.is_active != False.
Hope this helps.

How to get user's phone number from python social auth(google-oauth2)

I use python social auth and django rest framework.
I want to fetch the user phone number.
Settings
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config('GOOGLE_ID')
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config('GOOGLE_SECRET')
SOCIAL_AUTH_RAISE_EXCEPTIONS = False
SOCIAL_AUTH_USER_MODEL = 'users.TransUser'
SOCIAL_AUTH_GOOGLE_OAUTH2_USER_FIELDS = ['email', 'firstname', 'lastname', 'phone_number']
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/user.phonenumbers.read',
'profile',
'email',
]
Ouput
{'access_token': 'xxxxxxxx',
'email': 'xxxxxxxx,
'email_verified': True,
'expires_in': 3582,
'family_name': 'xxxxxxx',
'given_name': 'xxxxx',
'id_token': 'xxxxxx',
'locale': 'es',
'name': 'xxxxxxx',
'picture': 'xxxxx',
'scope': 'https://www.googleapis.com/auth/userinfo.email '
'https://www.googleapis.com/auth/user.phonenumbers.read '
'https://www.googleapis.com/auth/userinfo.profile openid',
'sub': 'xxxxxx',
'token_type': 'Bearer'}
but never phone number.
I use user's phone number to registration it.
I activated people APi in google console.
Thx you

Django Allauth, Twitter Scope

I'd like to get the user email from the twitter oauth. So I requested this in the app settings.
I added the scope (to settings.py):
SOCIALACCOUNT_PROVIDERS = {
'linkedin': {
'SCOPE': [
'r_emailaddress',
'r_basicprofile',
'r_fullprofile',
],
'PROFILE_FIELDS': [
'id',
'first-name',
'last-name',
'positions',
'email-address',
'picture-url',
'public-profile-url',
'headline',
'skills',
'summary',
'location',
'industry',
'positions',
'company',
'specialties',
'public-profile-url',
],
'LOCATION_FIELDS': [
'location',
],
'POSITION_FIELDS': [
'company',
]
},
'twitter': {
'SCOPE': ['email'],
},
}
However, I'm still having the user data like the name, picture ..etc but not the email.
Any suggestion ?

How to create a project sheet via the python SDK

I'm trying to create new project sheets in a folder, however I can't find a way to ensure the sheet is a project sheet.
Here is my code so far:
def create_resource_sheet(name):
""" Create a new resource sheet.
:param name:
:return:
"""
folder_id = get_resource_folder_id()
# TODO: Find and delete existing sheet with this name
resource_sheet = SS.models.Sheet({
'name': name,
# 'gantt_enabled': True, # This was added as an attempt to force it to a project sheet, but error 1032
'columns': [{
'title': 'Task',
'type': 'TEXT_NUMBER',
'primary': True,
'width': 200
}, {
'title': 'Status',
'type': 'PICKLIST',
'options': ['wtg', 'hld', 'ip', 'rdy', 'rev', 'fin', 'omt'], # TODO: Update this list
'width': 180
}, {
'title': '% Complete',
'type': 'TEXT_NUMBER',
'tag': ['GANTT_PERCENT_COMPLETE'],
'width': 85
}, {
'title': 'Assigned To',
'type': 'CONTACT_LIST',
'tag': ['GANTT_ASSIGNED_RESOURCE', 'GANTT_DISPLAY_LABEL'],
'width': 150
}, {
'title': '% Use',
'type': 'TEXT_NUMBER',
'tag': ['GANTT_ALLOCATION'],
'width': 60
}, {
'title': 'Days',
'type': 'DURATION',
'tag': ['GANTT_DURATION'],
'width': 70
}, {
'title': 'Start',
'type': 'ABSTRACT_DATETIME',
'tag': ['CALENDAR_START_DATE', 'GANTT_START_DATE'],
'width': 80
}, {
'title': 'Start',
'type': 'ABSTRACT_DATETIME',
'tag': ['CALENDAR_START_DATE', 'GANTT_START_DATE'],
'width': 80
}, {
'title': 'Finish',
'type': 'ABSTRACT_DATETIME',
'tag': ['CALENDAR_END_DATE', 'GANTT_END_DATE'],
'width': 80
}, {
'title': 'Type',
'type': 'TEXT_NUMBER',
'width': 150
}, {
'title': 'Comments',
'type': 'TEXT_NUMBER',
'width': 700
}
]
})
response = SS.Folders.create_sheet_in_folder(folder_id, resource_sheet)
new_sheet = response.result
return new_sheet
I am getting the following error code:
smartsheet.exceptions.ApiError: {"result": {"shouldRetry": false,
"code": 1142, "name": "ApiError", "errorCode": 1142, "recommendation":
"Do not retry without fixing the problem. ", "message": "Column type
DURATION is reserved for project sheets and may not be manually set on
a column.", "refId": "6gurrzzwhepe", "statusCode": 400}}
Is there a way I can create project sheets from scratch?
I have tried setting gantt_enabled to true but that just triggered a different error, so did setting 'project_settings'.
I have tried creating the sheet with just the primary column, then update_sheet to set project settings, which tells me: To set projectSettings, you must first enable dependencies on the sheet.
I have tried setting dependencies enabled, both directly in the create_sheet and in update_sheet, but both return: The attribute(s) sheet.dependenciesEnabled are not allowed for this operation.
I'm going to keep trying things, but I'm getting out of ideas.
Create the sheet from a template, either using the global project template or a user defined template if you want to customize.
templates = SS.Templates.list_public_templates()
for template in templates.data:
if template.global_template ==
smartsheet.models.enums.GlobalTemplate.PROJECT_SHEET:
break
sheet = smartsheet.models.Sheet({
'name': name,
'from_id': template.id
})
resource_sheet = SS.Folders.create_sheet_in_folder(folder_id, sheet)
If you want to customize create a project sheet using the Smartsheet web UI, make your changes and then Save As Template. Once you have the template, grab the ID from the Properties if you don't want to search for it, or SS.Templates.list_user_created_templates().
You cannot create a new dependency-enabled sheet through the API. You'll need to manually create a template and then use the API to make a copy.

"The provided key element does not match the schema" when writing into a table in DynamoDB

I followed these aws documents in order to set up my DynamoDB table:
creating table
loading the data into the table
Initially I created the table without any concern and the table structure would look like this:
Name > String
(Primary Key)
Category > String
Threads > Number
Messages > Number
Views > Number
When I tried to load the data, which was given on the 2nd hyperlink above, it throws up an exception saying:
An error occurred (ValidationException) when calling the
BatchWriteItem operation: The provided key element does not match the
schema
I did use the following command via the aws cli:
aws dynamodb batch-write-item --request-items file:///home/kula/Documents/aws/sampledata/Forum.json
This is the json file I'm trying to load, which I copied it from aws.
I also had a look into this ticket, and removed the quotes for numbers but still did not have any luck. Where am I going wrong?
Any help would be appreciated.
I apparently ended up creating python scripts to create table and load data into it.
Creating table:
import boto3
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
table = dynamodb.create_table(
TableName='users',
KeySchema=[
{
'AttributeName': 'username',
'KeyType': 'HASH'
},
{
'AttributeName': 'last_name',
'KeyType': 'RANGE'
}
],
AttributeDefinitions=[
{
'AttributeName': 'username',
'AttributeType': 'S'
},
{
'AttributeName': 'last_name',
'AttributeType': 'S'
},
],
ProvisionedThroughput={
'ReadCapacityUnits': 1,
'WriteCapacityUnits': 1
}
)
# Wait until the table exists.
table.meta.client.get_waiter('table_exists').wait(TableName='users')
Loading data into the table:
#!/usr/bin/python
import boto3
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
table = dynamodb.Table('users')
with table.batch_writer() as batch:
batch.put_item(
Item={
'account_type': 'standard_user',
'username': 'johndoe',
'first_name': 'John',
'last_name': 'Doe',
'age': 25,
'address': {
'road': '1 Jefferson Street',
'city': 'Los Angeles',
'state': 'CA',
'zipcode': 90001
}
}
)
batch.put_item(
Item={
'account_type': 'standard_user',
'username': 'bobsmith',
'first_name': 'Bob',
'last_name': 'Smith',
'age': 18,
'address': {
'road': '3 Madison Lane',
'city': 'Louisville',
'state': 'KY',
'zipcode': 40213
}
}
)
batch.put_item(
Item={
'account_type': 'super_user',
'username': 'alicedoe',
'first_name': 'Alice',
'last_name': 'Doe',
'age': 27,
'address': {
'road': '1 Jefferson Street',
'city': 'Los Angeles',
'state': 'CA',
'zipcode': 90001
}
}
)
print(table.creation_date_time)
Hope this helps someone!
I ran into a similar issue when trying to batch insert via aws dynamodb batch-write-item --request-items file://data/sample_services_data.json
It turns out that your primary partition key is case sensitive. In this scenario below, '77' will fail the import. If you change it to 'id' instead of 'Id' it will import without throwing the schema error.
{
"PutRequest": {
"Item": {
"Id": { "S": "77" },
"name": {"S":"Amazon Web Services"},
"language": {"S":"Python"},
"description": {"S":"Awesome super service"}
}
}
},
{
"PutRequest": {
"Item": {
"id": {"S":"99"},
"name": {"S":"Epic Service"},
"language": {"S":"NodeJS"},
"description": {"S":"Awesome epic service"}
}
}
}