How to send HttpResponse after email sent - django

I try to send an email with django , its working fine but i want to send a HttpReponse or somthing like that after the email sent , is that possible to keep using thread for that ?
class EmailThread(threading.Thread):
def __init__(self, subject, html_content, recipient_list, sender,name):
self.subject = subject
self.recipient_list = recipient_list
self.html_content = html_content
self.sender = sender
threading.Thread.__init__(self)
self.name= name
def run(self):
msg = EmailMessage(self.subject, self.html_content, self.sender, self.recipient_list)
msg.attach_file('/tmp/{username}.{filename}'.format(username=self.name,filename='proformas')+ '.pdf')
msg.content_subtype = "html" # Main content is now text/html
msg.encoding = 'utf-8'
if(msg.send()):
print('yes')
return HttpResponse('SENT')
def send_mail(request,pk):
commande = get_object_or_404(Commande,id=pk)
name = commande.Client.Raison_social
html_nadjib = render_to_string('Proformas/msg.html',{'raison_social':name,'Date':datetime.date.today()})
to_emails = ['adzadadazda#outlook.com']
subject = "azdzadaz"
sender = 'aazdazdazadazdb#gmail.com'
# EmailThread(subject, html_nadjib, to_emails, sender, name).start()
if(EmailThread(subject, html_nadjib, to_emails, sender, name).start()):
return HttpResponse('SENT')
else:
return HttpResponse('not sent')

Related

ValueError at /success Invalid address in django EmailMultiAlternatives

I want sent to multiple email but i got this raise ValueError('Invalid address "%s"' % addr)
ValueError: Invalid address "['ex1#gmail.com', 'ex2#gmail.com', 'ex404#gmail.com']"
email_id = ["ex1#gmail.com","ex2#gmail.com","ex404#gmail.com"]
username = name
email = email_id
######################### mail system ####################################
htmly = get_template('email/Email.html')
d = {
's_id' : s_id,
'username': username,
'tran_id' : tran_id,
'amount' : amount
}
subject, from_email, to = 'welcome', 'your_email#gmail.com', email
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, html_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
You send array type to an another array, So array dimension was changed.
Please check like this.
email_id = ["ex1#gmail.com","ex2#gmail.com","ex404#gmail.com"]
username = name
email = email_id
######################### mail system ####################################
htmly = get_template('email/Email.html')
d = {
's_id' : s_id,
'username': username,
'tran_id' : tran_id,
'amount' : amount
}
subject, from_email, to = 'welcome', 'your_email#gmail.com', email
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, html_content, from_email, to)
msg.attach_alternative(html_content, "text/html")
msg.send()
As other pointed out, you shouldn't enclose to in square brackets because it was already a list of strings, which is exactly what the parameter expects. See this example:
msg = EmailMultiAlternatives("subject", html_content, "from##gmail.com", ["to##gmail.com", "to2##gmail.com", "to3##gmail.com"])

Django rest framework custom return response

So I have this custom register API which registers a user, but when user successfully register, I want it to have this message "You have successfully register an account!" But I tried a different method but get an error instead.
serializer.py
class UserCreate2Serializer(ModelSerializer):
email = EmailField(label='Email Address')
valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p']
birthTime = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True, required=False)
class Meta:
model = MyUser
fields = ['username', 'password', 'email', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'birthTime']
extra_kwargs = {"password": {"write_only": True}}
def validate(self, data): # to validate if the user have been used
email = data['email']
user_queryset = MyUser.objects.filter(email=email)
if user_queryset.exists():
raise ValidationError("This user has already registered.")
return data
def create(self, validated_data):
username = validated_data['username']
password = validated_data['password']
email = validated_data['email']
first_name = validated_data['first_name']
last_name = validated_data['last_name']
gender = validated_data['gender']
nric = validated_data['nric']
birthday = validated_data['birthday']
birthTime = validated_data['birthTime']
user_obj = MyUser(
username = username,
email = email,
first_name = first_name,
last_name = last_name,
gender = gender,
nric = nric,
birthday = birthday,
birthTime = birthTime,
)
user_obj.set_password(password)
user_obj.save()
return validated
views.py
class CreateUser2View(CreateAPIView):
permission_classes = [AllowAny]
serializer_class = UserCreate2Serializer
queryset = MyUser.objects.all()
I tried changing this into the serializer
user_obj.set_password(password)
user_obj.save()
content = {'Message': 'You have successfully register an account'}
return content
But got an error instead. I'm unsure how to do the custom response as I only know it is to be done on views.py.
But if I do this on view:
class CreateUser2View(CreateAPIView):
permission_classes = [AllowAny]
serializer_class = UserCreate2Serializer
queryset = MyUser.objects.all()
def post(self, request):
content = {'Message': 'You have successfully register'}
return Response(content, status=status.HTTP_200_OK)
It will show this even if the validation is incorrect. Please help me as I'm still inexperienced in DRF.
class CreateUser2View(CreateAPIView):
permission_classes = [AllowAny]
serializer_class = UserCreate2Serializer
queryset = MyUser.objects.all()
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response({'Message': 'You have successfully register'}, status=status.HTTP_201_CREATED, headers=headers)
from rest_framework import status
from rest_framework.views import exception_handler as base_handler
def exception_handler(exception, context):
"""
Django rest framework for custom exception handler
#exception : Exception
#context : Context
"""
response = base_handler(exception, context)
if response is not None:
response = custom_response(response)
return response
def serializer_errors(data):
"""
Django rest framework serializing the errors
#data : data is python error dictionary
"""
errors = {}
got_msg = False
message = "Bad request."
if isinstance(data, dict):
for key, value in data.items():
try:
if isinstance(value, list):
value = ", ".join(value)
except Exception:
pass
if not got_msg:
if value:
message = value
got_msg = True
errors[key] = value
if not isinstance(message, str):
message = "Bad request"
return errors, message
def error(source, detail, code):
"""
Create python dictionary of error
#source : Where coming the error
#detail : Error detail information
"""
error = {}
error["source"] = source
error["detail"] = detail
if code:
error["code"] = code
return error
def custom_response(response):
"""
Modification the response of django rest framework
#response : Return response
"""
modified_data = {}
modified_data["code"] = response.status_code
modified_data["status"] = get_status(response.status_code)
data, message = serializer_errors(response.data)
modified_data["message"] = message
modified_data["errors"] = data
response.data = modified_data
return response
def get_status(status_code):
"""
Return result base on return http status
#status_code : HTTP status code
"""
result = ""
if status_code == status.HTTP_200_OK:
result = "Success"
elif status_code == status.HTTP_201_CREATED:
result = "Instance create"
elif status_code == status.HTTP_204_NO_CONTENT:
result = "Instance deleted"
elif status_code == status.HTTP_403_FORBIDDEN:
result = "Forbidden error"
elif status_code == status.HTTP_404_NOT_FOUND:
result = "Instance not found"
elif status_code == status.HTTP_400_BAD_REQUEST:
result = "Bad request"
elif status_code == status.HTTP_401_UNAUTHORIZED:
result = "Unauthorized request"
elif status_code == status.HTTP_500_INTERNAL_SERVER_ERROR:
result = "Internal server error"
else:
result = "Unknown error"
return result

django twilio for number phone confirmation returns exception in send function

I got an exception when i create a sms to send
here is my functions
def send_sms(to_number, body):
account_sid = settings.TWILIO_ACCOUNT_SID
auth_token = settings.TWILIO_AUTH_TOKEN
twilio_number = '+15005550006'
client = TwilioRestClient(account_sid, auth_token)
try :
client.messages.create(to=to_number,
from_=twilio_number,
body=body)
except Exception as e:
print e.message
def generate_code():
return str(random.randrange(100000, 999999))
def send_confirmation_code(request,to_number):
verification_code = generate_code()
send_sms(to_number, verification_code)
request.session['verification_code'] = verification_code
return verification_code

How to resend letter if email not confirmed, FLASK?

Am trying to resend email to any one that not yet confirmed his account .
models.py
class Subscribers(Base):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(50))
confirmed = db.Column(db.Boolean(), default=False)
def confirm(self, token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)
except:
return False
if data.get('confirm') != self.id:
return False
self.confirmed = True
db.session.add(self)
return True
def generate_confirmation_token(self, expiration=3600):
s = Serializer(app.config['SECRET_KEY'], expiration)
return s.dumps({'confirm': self.id})
def get_token(self, expiration=1800):
s = Serializer(app.config['SECRET_KEY'], expiration)
return s.dumps({'email': self.id}).decode('utf-8')
#staticmethod
def verify_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)
except:
return None
id = data.get('email')
if id:
return User.query.get(id)
return None
This is the function where the confirmation process handled:
#app.route('/send-confirmation/<email>/<token>')
def confirm(token,email):
subre = Subscribers.query.filter_by(email=email).first()
if subre.confirmed:
flash('Э.почта уже подтверждена.')
return redirect(url_for('index'))
if subre.confirm(token):
subre.confirmed = True
db.session.add(subre)
db.session.commit()
send_email(subre.email, 'Благодарим Вас за подписку на наш сайт', 'auth/subscribe/thanks', subre=subre, token=token)
flash('Вы подтвердили свою электронную почту, спасибо!')
else:
flash('Ссылка для подтверждения является недействительным или истек.')
return redirect(url_for('index'))
Tell now everything is working very well, am trying to fetch each account that not yet confirmed by sending them another message asking them to confirm there account, here is the function :
#app.before_request
def resend_confirmation():
subscribers = Subscribers.query.filter_by(confirmed=False)
for sub in subscribers:
email = sub.email
token = email.generate_confirmation_token()
send_email(email, 'Подтверждение по электронной почте было отправлено Вам по электронной почте.',
'auth/email/resend', email=email, token=token)
Here am getting an error says:
AttributeError: 'unicode' object has no attribute 'generate_confirmation_token'
i tried to add __unicode__ function in the model but without avail .
Please any help .
You are trying to call generate_confirmation_token method on email, but you should use Subscribers instance:
#app.before_request
def resend_confirmation():
subscribers = Subscribers.query.filter_by(confirmed=False)
for sub in subscribers:
token = sub.generate_confirmation_token()
send_email(sub.email, 'Подтверждение по электронной почте было отправлено Вам по электронной почте.',
'auth/email/resend', email=email, token=token)

Django: How can I download images from Base64ImageField?

I can use json format to upload images with Base64ImageField (by POST), but now I want to download images in the same way (by POST). When I POST a image to "driver_photo", for example:
"R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
,the image would save as "driver_photo":"driver_photos/2016/05/20/d2821170-662.gif".
My question is how could I open the file , encode it for convenient transmition by Base64ImageField and POST them.
Below is my serializer.py
class PassengerDataSerializer(serializers.ModelSerializer):
passenger_photo = Base64ImageField(
max_length=None, use_url=True,
)
class Meta:
model = PassengerData
fields = ("passenger_name","passenger_phone", "passenger_photo")
class TaxiDriverDataSerializer(serializers.ModelSerializer):
PassengerDatas = PassengerDataSerializer( many=True )
driver_photo = Base64ImageField(
max_length=None, use_url=True,
)
class Meta:
model = TaxiDriverData
fields = ("pk","fingerprint","driver_name","driver_photo","PassengerDatas")
def create(self, validated_data):
taxiDriverData = TaxiDriverData.objects.create(fingerprint = validated_data['fingerprint'],
driver_name = validated_data['driver_name'],
driver_photo = validated_data['driver_photo'],
)
taxiDriverData.save()
Passenger_Datas = validated_data.pop('PassengerDatas')
for passenger in Passenger_Datas:
passengerdata = PassengerData.objects.create(passenger_name = passenger.get('passenger_name'),
passenger_phone = passenger.get('passenger_phone'),
passenger_photo = passenger.get('passenger_photo'), )
passengerdata.taxi_driver_data_id = taxiDriverData
passengerdata.save()
return taxiDriverData
def update(self, instance, validated_data):
instance.fingerprint = validated_data['fingerprint']
instance.driver_name = validated_data['driver_name']
instance.driver_photo = validated_data['driver_photo']
instance.save()
return instance
views.py
#api_view(['GET','POST'])
def taxi_driver_list(request, format=None):
if request.method=="GET":
TaxiDriverDatas =list(TaxiDriverData.objects.all())
serializer = TaxiDriverDataSerializer(TaxiDriverDatas,many=True)
return Response(serializer.data)
elif request.method == 'POST':
#print (request.body)
serializer = TaxiDriverDataSerializer(data=request.data)
#, files=request.FILES
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#api_view(['GET', 'PUT', 'DELETE'])
def taxi_driver_detial(request,pk, format=None):
try:
Taxi_Driver_Data = TaxiDriverData.objects.get(pk=pk)
except TaxiDriverData.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == "GET":
serializer = TaxiDriverDataSerializer(Taxi_Driver_Data)
return Response(serializer.data)
elif request.method == "PUT":
serializer = TaxiDriverDataSerializer(Taxi_Driver_Data,data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
elif request.method == "DELETE":
Taxi_Driver_Data.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
models.py
class TaxiDriverData(models.Model):
fingerprint = models.CharField(max_length=30, default="")
driver_name = models.CharField(max_length=30, default="")
driver_photo = models.ImageField(upload_to ="driver_photos/%Y/%m/%d/", null=True ,blank=True)
class PassengerData(models.Model):
taxi_driver_data_id = models.ForeignKey(TaxiDriverData, related_name='PassengerDatas', null=True)
passenger_name = models.CharField(max_length=100, default="")
passenger_phone = models.CharField(validators=[phone_regex], blank=True, max_length=16)
passenger_photo = models.ImageField(upload_to ="passenger_photos/%Y/%m/%d/", null=True ,blank=True )
Thanks for help.
It is highly recommended to use POST instead of GET to send/receive Base64 images, since Base64 images are converted to String with length of string varying upto 15000 characters. If you are using the GET method, you are limited to a maximum of 2,048 characters.
Save the image
import base64
imgdata = base64.b64decode(imgstring)
filename = 'some_image.jpg' # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
f.write(imgdata)
Edit1
You could do something like this to save the image
import base64
import datetime
def save_image(request):
b64_image = request.POST['driver_photo'] #key that is being used to send the data
imgdata = base64.b64decode(b64_image)
var = datetime.datetime.now().strftime("%d%m%Y%H%M%S") #This will give unique values everytime. Values are based on current datetime
filename = "PATH_TO_SAVE_FILE" + var +'.jpg'
with open(filename, 'wb') as f:
f.write(imgdata)
Edit 2
POST Request in Android
HttpClient httpclient = new DefaultHttpClient();
String responseStr="";
String URL=Constants.API_URL;#URL where request needs to be sent
HttpPost httppost = new HttpPost(URL);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", pick_up_id));
nameValuePairs.add(new BasicNameValuePair("driver_photo", strPhoto));#image in form of Base64 String which you need to send
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
String responseBody = EntityUtils.toString(entity);
responseStr=responseBody;
}
break;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
System.out.println("this is response "+responseStr);