我的第一次(真的?)程序。
客户端通过发送用户凭据来获取标头的令牌,从而连接到Django restframework。然后,用户可以将图像从OS文件夹拖放到终端中,然后按enter键,然后编写一个标题供其上传。
从服务器获取图像(S) URL,然后将其转化为字节数组中列出的标记。这个字节数组被加载到一个可以用系统的默认编辑器或Vim编辑的tempfile中。当它被保存和关闭时,它被转换成html并发布文章。
import requests
import tempfile
import os
import pypandoc
import json
from getpass import getpass
from subprocess import call
EDITOR = os.environ.get('EDITOR', 'vim')
ARTICLE_URL = 'http://127.0.0.1:8000/api/articles/'
IMAGE_URL = 'http://127.0.0.1:8000/api/media/images/'
TOKEN_URL = 'http://127.0.0.1:8000/api-auth-token/'
def obtain_token(username, password):
"""Authenticate and obtain token"""
data = {'username': username, 'password': password}
req = requests.post(TOKEN_URL, data=data)
res = req.json()
token = res['token']
headers = {'Authorization': 'Token {}'.format(token)}
return headers
"""
Ask for user credentials to set header, not sure how to
place this code in a functional way
"""
username = input("Username: ")
password = getpass()
headers = obtain_token(username=username, password=password)
def image_upload(img_file, img_title):
"""Upload image with title"""
files = {'image': img_file}
payload = {'title': img_title}
upload = requests.post(IMAGE_URL, files=files, data=payload,
headers=headers)
return upload
md_urls = bytearray()
def img_docload():
"""
Get the latest uploaded image and convert it
to a html string so that pypandoc again can make
it into markdown, then extend each to the bytearray.
"""
get_url = requests.get(IMAGE_URL)
get_json = json.loads(get_url.content)
clean = get_json[-1]['image']
md_html = ""
md = pypandoc.convert_text(md_html, 'md', format='html')
md_urls.extend(md.encode())
def article(headline, summary):
"""
Make a tempfile and write the list of markdown inserts,
then open it in Vim or any default editor. Save and quit
to convert from markdown to html and upload the article.
"""
with tempfile.NamedTemporaryFile(suffix='.md') as tmp:
tmp.write(md_urls)
tmp.flush()
call([EDITOR, tmp.name])
tmp.seek(0)
edited = tmp.read()
article = edited.decode('utf-8')
content = pypandoc.convert_text(article, 'html', format='md')
payload = {
'headline': headline,
'summary': summary,
'content': content,
}
upload = requests.post(ARTICLE_URL, json=payload, headers=headers)
return upload
def main():
while True:
action = input("Upload image? (k): ")
if action == 'k':
img_file = open(input("Image - Filename: ").strip('\''), 'rb')
img_title = input("Image - Title: ")
image_upload(img_file=img_file, img_title=img_title)
img_docload()
continue
else:
headline = input("Article - Headline: ")
summary = input("Article - Summary: ")
article(headline=headline, summary=summary)
print("Article is published")
break
main()obtain_token函数及其I/O?总的来说,我想知道我犯的所有错误
发布于 2019-08-27 07:53:05
ARTICLE_URL = 'http://127.0.0.1:8000/api/articles/‘IMAGE_URL = 'http://127.0.0.1:8000/api/media/images/’TOKEN_URL = 'http://127.0.0.1:8000/api-auth-token/‘
这里的重复可能是有害的。如果您移动服务器,那么有三个地方需要编辑和保持同步。通过减少重复,更容易应对这样的举动:
BASE_URL = 'http://127.0.0.1:8000/api/'
ARTICLE_URL = BASE_URL + 'articles/'
IMAGE_URL = BASE_URL + 'media/images/'
TOKEN_URL = BASE_URL + 'api-auth-token/'很高兴看到with关键字被有效地使用,以确保资源被正确清理,即使抛出异常;保持好习惯!;-)
在main()中,while True具有误导性;实际流程是,我们重复第一个分支多次,然后精确地重复第二个分支一次。我们可以重组循环,使之更加清晰:
def main():
while input("Upload image? (k): ") == 'k':
img_file = open(input("Image - Filename: ").strip('\''), 'rb')
img_title = input("Image - Title: ")
image_upload(img_file=img_file, img_title=img_title)
img_docload()
headline = input("Article - Headline: ")
summary = input("Article - Summary: ")
article(headline=headline, summary=summary)
print("Article is published")没有continue和break,就更容易理解控制流;只使用这些关键字作为最后手段!
只有当我们将其作为程序直接执行,而不是将其作为模块导入时,我们才应该运行main():
if __name__ == '__main__':
main()我们还需要将用户名/密码请求移动到main()中,我们可能希望将headers作为参数传递,而不是共享全局变量。(我假设在明文中传递密码是一个弱点,这是您所使用的API强加给您的--在设计接口时,绝不能像这样不安全地传递身份验证器!)
https://codereview.stackexchange.com/questions/197406
复制相似问题