For Quine posts ** here **
I had a lot of trouble escaping when writing quine code as a string using ʻexec`. The code in the article Unicode escapes double quotes and back quotes. If there is a smarter way, please let us know in the comments.
[Version information (sys.version
)]
3.8.2 (default, Apr 23 2020, 14:22:33)
[GCC 8.3.0]
quineRequest.py
authorization_token = 'Bearer 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdi'
z="\\"
escape_def_code = """
def escape(s):
return s.replace(\u0022'\u0022, z + 'u0027').replace('\u0022', z * 2 + 'u0022').replace('\u0060', z * 2 + 'u0060')
"""
exec_code = """
import sys
import requests
import json
url = 'https://qiita.com/api/v2/items'
headers = {{
'Authorization': '{0}',
'Content-Type': 'application/json'
}}
title = 'Quine post with Qiita API(Python)'
body = '''
For Quine posts**[Here](https://qiita.com/j5c8k6m8/items/bc2324ef036729da1a28)**
\u0060exec\I had a lot of trouble escaping when writing quine code as a string using u0060.
The code in the article Unicode escapes double quotes and back quotes.
If there is a smarter way, please let us know in the comments.
[version information(\u0060sys.version\u0060) ]
**'''
body += sys.version
body += '''**
#Code that ran the API in this article
\u0060\u0060\u0060 python:quineRequest.py
authorization_token = 'Bearer 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdi'
'''
body += ('z=\u0022' + (z * 2) + '\u0022')
body += '''
escape_def_code = \u0022\u0022\u0022{1}\u0022\u0022\u0022
exec_code = \u0022\u0022\u0022{2}\u0022\u0022\u0022
exec_exec_code = \u0022\u0022\u0022{3}\u0022\u0022\u0022
{3}
\u0060\u0060\u0060
'''
tag = [{{'name': 'Qiita'}}, {{'name': 'Python'}}, {{'name': 'quine'}}, {{'name': 'QiitaAPI'}}, {{'name': 'quine post'}}]
post_data = {{
'private': False,
'body': body,
'title': title,
'tags': tag,
}}
r = requests.post(url, headers=headers, data=json.dumps(post_data))
"""
exec_exec_code = """
exec(escape_def_code)
exec(exec_code.format(authorization_token, escape(escape_def_code), escape(exec_code), escape(exec_exec_code)))
"""
exec(escape_def_code)
exec(exec_code.format(authorization_token, escape(escape_def_code), escape(exec_code), escape(exec_exec_code)))
Recommended Posts