0

I'm trying to add CSS to the HTML that my python code generates. This line causes an error when I post the HTML:

html += '<link rel=\'stylesheet\' href=\'{{ url_for(\'static\', filename=\'css/main.css\') }}\'>'

I also tried putting the quotes on the outside, I get the same error:

html += "<link rel=\'stylesheet\' href=\'{{ url_for(\'static\', filename=\'css/main.css\') }}\'>"

The error I'm getting is:

requests.exceptions.HTTPError: 400 Client Error: Bad Request for url:

if I remove that one line I can PUT to the web page.

This is the code that writes the HTML to the page:

def write_data_to_confluence(auth, html, pageid, title = None):
    info = get_page_info(auth, pageid)
    ver = int(info['version']['number']) + 1
    ancestors = get_page_ancestors(auth, pageid)
    anc = ancestors[-1]
    del anc['_links']
    del anc['_expandable']
    del anc['extensions']
    if title is not None:
        info['title'] = title
    data = {
        'id' : str(pageid),
        'type' : 'page',
        'title' : info['title'],
        'version' : {'number' : ver},
        'ancestors' : [anc],
        'body'  : {
            'storage' :
            {
                'representation' : 'storage',
                'value' : str(html)
            }
        }
    }
    data = json.dumps(data)
    url = '{base}/{pageid}'.format(base = BASE_URL, pageid = pageid)
    r = requests.put(
        url,
        data = data,
        auth = auth,
        headers = { 'Content-Type' : 'application/json' }
    )
    r.raise_for_status()
    print("Wrote '%s' version %d" % (info['title'], ver))
    print("URL: %s%d" % (VIEW_URL, pageid))

I think I am quoting it wrong. I tried a couple different ways, but have yet to get it right. How can I quote this correctly?

4
  • Try using html += "..." so you don't have to escape all the single quotes inside the string. That should make it easier to see the real error. Commented Jun 10, 2019 at 16:36
  • html += """<link rel='stylesheet' href="{{ url_for('static', filename='css/main.css') }}">""" Commented Jun 10, 2019 at 16:36
  • I've tried all of the suggestions in this thread. I'm still getting the same error, unfortunately. This is the exact error that I'm getting: raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://wiki.us.cworld.company.com/rest/api/content/138335201 Commented Jun 10, 2019 at 16:48
  • I just found out that url_for() depends on flask being installed. I will try installing that and see if I can get this to work! Commented Jun 10, 2019 at 20:07

2 Answers 2

1

Try this approach,

html += "<link rel=\"stylesheet\" href=\"{{ url_for('static', filename='css/main.css') }}\">"

Escaping single quotes is not required as the string is enclosed in double quotes. The attribute values are enclosed in double quotes.

or, using triple quotes

html += """<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">"""
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks! I tried both your suggestions. I still get this error when I post:Traceback (most recent call last): File "C:\Users\tdunphy\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\models.py", line 940, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://wiki.us.cworld.company.com/rest/api/content/138335201
It might be due to a different reason. Can you share the code which handles the request?
Sure! I've just posted the code that writes the page to confluence in the OP.
Have you tried to post a request to the API using cURL or any other similar tool? It could be that the problem isn't with the html data you're sending, but something else.
I tried printing out the HTML variable from the code. Think this will help us get to the bottom of it? pastebin.com/p1XjQ7Hk
|
0

If you want to use string interpolation ({{ url_for...) then you need to use f-strings: f'interpolation: {{url_for(whatever)}}'

Also you can use double-quoted strings and not bother escaping every single quote: print("Single 'quotes' are fine here")

In more complex cases you can use multiline stings, they can contain newlines and other quote markers inside them, ''' this 'is' "ok" '''. There are '''string''' and """string""" versions, functionally the same.

10 Comments

Thank you. I tried both of these (one at a time), and I'm still getting the same error: html += """ <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"> """ html += ''' <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"> '''
@bluethundr You're still not using format-strings. If you add f before the opening quote: f""" my sting """ it should work. Right now {{ url_for... is just a text, it is not interpreted by python as a code
ok, I tried putting an 'f' in front of the quotes and I'm still getting the same error. I tried each of these lines: ` html += f""" <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"> """ html += f''' <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"> '''`
Wait a second. Are you sure that you meant PUT and not POST request?
Sorry yes, I'm using PUT in the request. Think I'll do any better with a POST request?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.