TypeError: The view function for ' ' did not return a valid response. The function either returned None or ended without a return statement [duplicate] - flask

This question already has answers here:
Flask view return error "View function did not return a response"
(3 answers)
Closed 12 days ago.
I am trying to learn flask API with basic user CRUD operations on mysql database. My fetch all users is working perfect. But with same DB creating user is giving TypeError
This is my create user endpoint. For db connection I am using flask-mysqldb
#app.route('/create', methods=['POST'])
def create_user():
try:
if not request.is_json:
return jsonify({"message": "Bad Request: Request body must be JSON ☠️ "}), 400
else:
data = request.get_json()
fname = data.get('first_name')
lname = data.get('last_name')
gender = data.get('gender')
email = data.get('email')
phone = data.get('phone')
country_code = data.get('country_code')
if fname and lname and email and gender and phone and country_code:
conn = mysql.connect()
cur = conn.cursor()
cur.execute("""INSERT INTO users (fname, lname, gender, email, phone_number, phone_country_code) VALUES (%s,%s,%c,%s,%s,%s) """.format(fname, lname, gender, email, phone_number, country_code))
conn.commit()
cur.close()
conn.close()
return jsonify({"message": "User created successfully 🥳 " }), 200
else:
return jsonify({"message": "Some data is missing 🙁 "}), 200
except Exception as e:
print(e)
I am getting JSON data inside if statement which is am passing through postman
{
"first_name" : "John",
"last_name" : "Doe",
"gender" : "M",
"email" : "john#fakedoe.com",
"phone" : "9876543210",
"country_code" : "UK"
}
Thanks in advance

on debug, I found the issue was with sql query. We could solve this TypeError issue by simply changing SQL query format.
cur.execute("""INSERT INTO users ( fname, lname, gender, email, phone_number, phone_country_code)
VALUES (%s, %s,%s,%s,%s,%s)""", (fname, lname, gender, email, phone, country_code))
conn.commit()
Hope this help whoever came across this issue.

Related

Angular + Django Backend. How to Log in base on user types in Django

I'm facing a problem on how to integrate user permission like if the is_superuser is False, then log in to Author component and if is_superuser is True, log in to Admin component in Angular. I hope someone can help.
What I want,
If the is_superuser is True in django, then log in to a Admin
component / admin dashboard
If the is_superuser is False in django, then log in to a Author
component / Author dashboard
class MyAuthToken(auth_views.ObtainAuthToken):
serializer_class = MyAuthTokenSerializer
#action(detail=True, methods=['POST'])
def post(self, request, *args, **kwargs):
response = super(MyAuthToken, self).post(request, *args, **kwargs)
token = Token.objects.get(key=response.data['token'])
user = CustomUser.objects.get(id=token.user_id)
users = json.dumps(UserSerializer(user).data)
id = json.loads(users)["id"]
email = json.loads(users)["email"]
is_superuser = json.loads(users)["is_superuser"]
return Response({'id': id, 'email': email, 'is_superuser': is_superuser,
'token': token.key})
finally solved my own problem. What I did was return a json response which will include the some user details to the front end. then call it on the front end.
Here's how I did it in my front end. I console log it to check the results
interface TokenObj {
id: number
email: string
is_superuser: boolean;
token: string;
}
_id: number;
_email: string;
_is_superuser: boolean;
_token: any;
mrToken: string;
loginUser() {
this.service.userLogin(this.authForm.value).subscribe(
(result: TokenObj) => {
this._token = this.cookieService.set('mr-token', result.token);
this._id = result.id
this._email = result.email
this._is_superuser = result.is_superuser
this._token = result.token
console.log("******** id " + this._id);
console.log("******** email " + this._email);
console.log("******** is_superuser " + this._is_superuser);
console.log("******** token " + this._token);
if (this._is_superuser === true && this._token){
this.router.navigateByUrl('/approuting');
}
else if (this._is_superuser === false && this._token){
this.router.navigateByUrl('/approuting/employee');
}
},
error => console.log(alert("wrong credentials"))
);
}
}
I really wanted to post my answer so I created a new account. I hope the other account can post answers soon. I also hope this will find beginner programmers who like me that is integrating angular and Django for a web development

How to fix "django.core.exceptions.FieldError:" when querying with "_startswith" filter in django views?

I am trying to get a queryset where the username starts with some name.
I have implemented the following code :
def searchUsers(request):
if request.is_ajax():
uname = request.GET['name']
print(uname)
user = User_Master.objects.filter(username_startswith = uname.title())
usr_jsn = json.loads(serializers.serialize('json', user))
return JsonResponse(usr_jsn)
Ajax call is succesfully running and I'm getting the searchkeyword printed in terminal.
But the error I'm getting is because of "_startswith" filter. This is the part from traceback.
django.core.exceptions.FieldError: Cannot resolve keyword 'username_startswith' into field. Choices are: contact_no, created_at, created_by, department, email, id, industry_segment, password, status, updated_at, updated_by, username
I have searched for my problem but none of the solutions worked.
it should be dundee(__) double underscore for lookups
user = User_Master.objects.filter(username__startswith = uname.title())

Regex validation code in not accepting in AWS lexbot validation

I used regex code for validating emails and phone numbers in lambda for validating AWS lexbot but it was throwing an error (An error has occurred: Invalid Lambda Response: Received error response from Lambda: Unhandled).
enter image description here
I had created 3 intents in this particular bot. In this 2 intents are working but one intent was not at all detecting because of this regex validation code. If I remove this regex validation code it was working fine.
This is the lambda code of intent where I am getting error.
""" --- Start greeting --- """
def validate_greeting_intent(usermood,phonenumber,email):
UserMood = ['okay', 'better', 'too gud', 'fine', 'gud', 'happy', 'good', 'great']
if usermood is not None and usermood.lower() not in UserMood:
return build_validation_result(False,
'UserMood',
'Hey start with good greeting conversation, please'
)
if not PHONE_REGEX.match(phonenumber):
return build_validation_result(
False,
'PhoneNumber',
'Please enter valid phone number which contains 10 digits'
)
if not EMAIL_REGEX.match(email):
return build_validation_result(
False,
'Email',
'Please enter valid email address'
)
return build_validation_result(True, None, None)
def greeting_intent(intent_request):
usermood = get_slots(intent_request)['UserMood']
phonenumber = get_slots(intent_request)['PhoneNumber']
email = get_slots(intent_request)['Email']
source = intent_request['invocationSource']
if source == 'DialogCodeHook':
slots = get_slots(intent_request)
validation_result = validate_greeting_intent(usermood,phonenumber,email)
if not validation_result['isValid']:
slots[validation_result['violatedSlot']] = None
return elicit_slot(intent_request['sessionAttributes'],
intent_request['currentIntent']['name'],
slots,
validation_result['violatedSlot'],
validation_result['message'])
# Pass the price of the pizza back through session attributes to be used in various prompts defined
# on the bot model.
output_session_attributes = intent_request['sessionAttributes'] if intent_request['sessionAttributes'] is not None else {}
if usermood is not None:
output_session_attributes['Price'] = len(usermood) * 5 # Elegant pricing model
return delegate(output_session_attributes, get_slots(intent_request))
return close(intent_request['sessionAttributes'],
'Fulfilled',
{'contentType': 'PlainText',
'content': 'What you want to order'})
""" --- End Greeting --- """

recipient_list send mail just to the first address in the list

I´m using signals to send mails to the users depending of some actions. In one of my signals I need to send the same mail to multiple users, my signal use post_save so for the parameter [recipient_list] I use this instance.email_list email_list is where I store the list of email addresses to send the mail, they are stored in this format user1#mail.com, user2#mail.com, user3#mail.com.
To send the emails I use EMAIL_HOST = 'smtp.gmail.com' the problem is that the only user who recive the email is the first one in the list. So I 'log in' in the gmail account to check the send emails section and actually in the "to" area of the email shows that was send to all the users in the list but the emails never arrive just for the first email address in the list.
I read that if google detect that the account sends a lot of messages could be blocked but only send like 5 emails at the same time and when I'm in the account never shows me some alert or something.
So the problem is how I send the emails or maybe some bad configuration of the gmail account?
Any help is really appreciated.
Sorry for my bad grammar.
EDIT: Here's my code.
forms.py
class MyForm(forms.Form):
userslist = forms.ModelChoiceField(queryset = User.objects.filter(here goes my condition to show the users), empty_label='List of users', label='Users', required=False)
emailaddress = forms.CharField(max_length=1000, label='Send to:', required=False)
comment = forms.CharField(widget=CKEditorUploadingWidget(), label="Comment:")
That form display a list of users to select the email address in the field emailaddress store the values. This is my Ajax to bring the email address:
views.py
class mails(TemplateView):
def get(self, request, *args, **kwargs):
id_user = request.GET['id']
us = User.objects.filter(id = id_user)
data = serializers.serialize('json', us, fields=('email'))
return HttpResponse(data, content_type='application/json')
And here's the <script> I use to populate the emailaddres field:
<script>
$('#id_userlist').on('change', concatenate);
function concatenate() {
var id = $(this).val();
$.ajax({
data: { 'id': id },
url: '/the_url_to_get_data/',
type: 'get',
success: function (data) {
var mail = ""
for (var i = 0; i < data.length; i++) {
mail += data[i].fields.email;
}
var orig = $('#id_emailaddress').val();
$('#id_emailaddress').val(orig + mail + ',');
}
})
}
</script>
The signal I use to send the mail is this:
#receiver(post_save, sender=ModelOfMyForm, dispatch_uid='mails_signal')
def mails_signal(sender, instance, **kwargs):
if kwargs.get('created', False):
if instance.emailaddress:
#Here goes the code for the subject, plane_message,
#from_email and template_message.
send_mail(subject, plane_message, from_email, [instance.emailaddress], fail_silently=False, html_message=template_message)
So if I select 4 users the info is save in this way in the database:
Then I 'log in' in the account to check the 'Sent Mail' section and check the detail of the mail and shows that was send to the 4 users but the only user who recibe the mail was the first in the list.
Your problem is that you are passing a comma-separated string of email addresses inside instance.emailaddress (first#gmail.com, second#hotmail.com, third#hotmail.com etc). Django expects a Python list of addresses, not a comma separated string. It will just ignore everything after the first comma.
Change your code as follows and it will work:
def mails_signal(sender, instance, **kwargs):
if kwargs.get('created', False):
if instance.emailaddress:
#Here goes the code for the subject, plane_message,
#from_email and template_message.
recipients = [r.strip() for r in instance.emailaddress.split(',')]
send_mail(subject, plane_message, from_email, recipients, fail_silently=False, html_message=template_message)

RPCError: dictionary update sequence element #0 has length 1; 2 is required on python

i wanted to insert new data into porstgresql using odooRPc i am having error like below
RPCError: dictionary update sequence element #0 has length 1; 2 is required
my python script code is :
def POST(self):
data = []
web.header('Access-Control-Allow-Origin', '*')
web.header('Access-Control-Allow-Credentials', 'true')
web.header('Content-Type', 'application/json')
auth = web.input()
print("auth")
print(auth)
name=auth['username']
pwd=auth['password']
city=auth['city']
eml=auth['eml']
mobile=auth['phone']
state_id=auth['state']
country_id=auth['country']
# print(type(auth['country']))
# country_id=auth.get('Country').get('id')
# country_id=auth['country'].get('id')
# print(country_id)
# state_id=auth['state']
# print(state_id)
odoo = odoorpc.ODOO('field.holisticbs.com',port=8069)
odoo.login('field.holisticbs.com','info#holisticbs.com','admin')
# Customer = odoo.execute_kw('res.partner','create',{'name':name,' email':eml,'mobile':mobile,' country_id':country_id,'state_id':state_id})
Customer = odoo.execute_kw('res.partner','create',{'name':name,' email':eml,'mobile':mobile})
print(Customer)
# Users = odoo.env['res.partner']
# user = Users.browse([int(idu)])
# print(user)
# Customer = odoo.execute_kw('res.user','create',{'login':eml,' password':pwd})
return json.dumps(Customer)
I have made my comments as below , kindly request you to find it as below it will help in your case:
Well there are many RPC Library (Python) for connecting with the API of Odoo/OpenERP:
xmlrpclib
odoorpc
erppeek
oerplib
openerplib..
In Your case You have chose the odoorpc.
Here is the code snippet for using it odoorpc:
import odoorpc
import json
domain ='localhost' #the domain
port=8069 #the active port
username = 'username' #the user name
password = 'password' #the user password
dbname = 'database_name' #the database
#Validate the credentials
odoo = odoorpc.ODOO(domain, port=port)
odoo.login(dbname, username, password)
#Login User details
user = odoo.env.user
print(user.name) # user name
print(user.company_id.name) # user company name
#Create a partner
user_data = odoo.execute('res.partner', 'create',
{'name':"PRAKASH",'
email':" prakashsharmacs24#gmail.com",
'mobile':"7859884833"})
print(user_data)
But i have also find you are using the method execute_kw so please use xmlrpclib if you want to use method execute_kw
Here is the code snippet for using it xmlrpclib:
import xmlrpclib
domain ='localhost' #the domain
port=8069 #the active port
username = 'username' #the user name
password = 'password' #the user password
dbname = 'database_name' #the database
#Validate the credentials
url='http://{domain}:{port}'.format(domain=domain,port=port)
login_url='{url}/xmlrpc/2/common'.format(url=url)
sock_common = xmlrpclib.ServerProxy(login_url)
uid = sock_common.login(dbname, username, password)
print sock_common.version()
print uid
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
#Validate the access rights
print models.execute_kw(dbname, uid, password,
'res.partner', 'check_access_rights',
['read'], {'raise_exception': False})
#Execute the query
print models.execute_kw(dbname, uid, password,
'res.partner', 'search',
[[['is_company', '=', True], ['customer', '=', True]]])
You can also refer this Link for knowing the difference between the RPC library
I hope this will help you ..