sendgrid-python icon indicating copy to clipboard operation
sendgrid-python copied to clipboard

Construct 'dynamic_template_data' field dynamically

Open Nicosan-K opened this issue 7 years ago • 9 comments

Issue Summary

I'm following: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/transactional_templates.md

I 'd like to construct message.dynamic_template_data dynamically. When not using strings as per example, I get python_http_client.exceptions.BadRequestsError: HTTP Error 400: Bad Request

Steps to Reproduce

1 - Create a Json object

dynamic_template_input = {'token' : 'this_a_key'}
json_string = json.dumps(dynamic_template_input)   # >>> {"token": "this_a_key"}
  1. Update message.dynamic_template_data field `message.dynamic_template_data = json_string'

  2. Send message, 400 error received

Alternative option tested: If instead manually construct a test string, I also get a 400 error. message.dynamic_template_data = f'{{"token": "{this_a_key}"}}'

Using message.dynamic_template_data with a string configuration, works correctly with not issues and Handlebars are accepted in email with 200 response.

Are you able to help?

Technical details:

  • sendgrid-python Version: 6.0.5
  • Python Version :3.7.2

Nicosan-K avatar May 28 '19 03:05 Nicosan-K

Hello @Nicosan-K,

I'm not sure I follow.

Are you trying to do something like this?

dynamic_subject = get_subject()
message.dynamic_template_data = {
    'subject': dynamic_subject,
    'name': 'Some One',
    'city': 'Denver'
}
message.dynamic_template_data['dynamic_key'] = dynamic_value()

thinkingserious avatar May 28 '19 17:05 thinkingserious

Hi Elmer,

thanks. Yes, something like above.

1-Your first example works, but requires to have a predefined set of keys (in the example subject, name, city).

2-Second is close; it would allow to add an arbitrary number of of keys, but when I run a test: message.dynamic_template_data['dynamic_key'] = 'test' I get Traceback >>> TypeError: 'NoneType' object does not support item assignment

3-What I originally tried was to pass a Json string, which gave a 400 error:

dynamic_template_input = {'dynamic1' : 'this_a_value', 'dynamic2': 'this_a_second_value'} # a python dict
message.dynamic_template_data = json.dumps(dynamic_template_input)  # use dict as input

thanks

Nicosan-K avatar May 29 '19 02:05 Nicosan-K

Hello @Nicosan-K,

For 1, you can do this:

dynamic_key = dynamic_key()
dynamic_value = dynamic_value()

message.dynamic_template_data = {
    dynamic_key: dynamic_value
}

If you want to do 2, you must first initialize the dict like so:

message.dynamic_template_data = {}
message.dynamic_template_data['dynamic_key'] = 'test'

thinkingserious avatar May 29 '19 02:05 thinkingserious

Hi @thinkingserious

1-With this option I still need to have a predefined number of dynamic keys. I'm looking for a variable number. Options two would would for me, within a loop.

2: Tried again, but still same issue -> does it work on your end? Do you need to import any library?

Traceback (most recent call last):  File "email_test.py", line 15, in <module>
    message.dynamic_template_data['token'] = dynamic_token
TypeError: 'NoneType' object does not support item assignment

Nicosan-K avatar May 30 '19 06:05 Nicosan-K

Hi @Nicosan-K,

Could you please the complete code that is not working? The only library you should need is this one.

With Best Regards,

Elmer

thinkingserious avatar Jun 03 '19 19:06 thinkingserious

Hi @thinkingserious ,

below is all the code I'm using:

file: email_test.py

import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

# ->> the template id as provided by Sendgrid, the to email, the from email and the api.
from config import template_id, from_email_config, to_email_config, SG_api_key

message = Mail(
    from_email=from_email_config,
    to_emails=to_email_config,
    html_content='<strong>and easy to do anywhere, even with Python</strong>')

message.template_id = template_id

message.dynamic_template_data = {}
message.dynamic_template_data['token'] = 'test'

try:
    sendgrid_client = SendGridAPIClient(SG_api_key)
    response = sendgrid_client.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
    print(message.dynamic_template_data)
    print(message.template_id)
except Exception as e:
    print(e.message)

Nicosan-K avatar Jun 03 '19 23:06 Nicosan-K

Hello @Nicosan-K,

This works:

import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email='[email protected]',
    to_emails='[email protected]',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')

message.template_id = 'd-142c5c8d375041b6bd2efd5d794db692'

template_data = {}
template_data['firstname'] = 'Elmer'
template_data['location'] = 'Irvine'
message.dynamic_template_data = template_data


try:
    sendgrid_client = SendGridAPIClient()
    response = sendgrid_client.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.to_dict)

Here is what my template looks like:

-<html>
<head>
	<title></title>
</head>
<body>
Hello {{ firstname }},
<br /><br/>
I'm glad you are trying out the template feature!
<br /><br/>
I hope you are having a great day in {{ location }} :)
<br /><br/>
</body>
</html>

I hope that helps!

thinkingserious avatar Jun 05 '19 18:06 thinkingserious

@thinkingserious

Thanks. I confirm this works. Input for 'message.dynamic_template_data' is Python dyct as you mentioned. You can close this ticket.

In separate note: I'm left with the footer to be configured. [Sender_Name] [Sender_Address], [Sender_City], [Sender_State] [Sender_Zip] Unsubscribe Unsubscribe Preferences

I can see #735 indicates that you need to export the template and replace '[]' with '{{}} Is is there any specific Mail Helper Class that you can use to pass the values instead? I vote that issue if still open. Exporting the template is not great.

Thanks, Nicolas

Nicosan-K avatar Jun 11 '19 02:06 Nicosan-K

Hello @Nicosan-K,

We don't currently have a Mail Helper Class for that. Please add your vote on #735 for that. Thanks!

With Best Regards,

Elmer

thinkingserious avatar Jun 11 '19 15:06 thinkingserious