问题
I'm an independent publisher on Apple News, and create articles using News Publisher. I was looking for some flexibility in how my articles are formatted and presented, and was wondering how to upload a JSON document for future articles - I've never worked with it before. Does anyone familiar with the service or the language know how to connect something like this to Apple News? I looked at their help section already, but came away with more questions than answers it seems. Thank you!
-Tyler
回答1:
A basic article looks like this
{
"version": "1.4",
"identifier": "sketchyTech_Demo",
"title": "My First Article",
"language": "en",
"layout": {},
"components": [
{
"role": "title",
"text": "My First Article"
},
{
"role": "body",
"text": "This is just over the minimum amount of JSON required to create a valid article in Apple News Format. If you were to delete the dictionary enclosing this text, you'd be there."
}
],
"componentTextStyles": {}
}
and is always saved as article.json
. Within the components array you can feature any of the Apple News Components. (Note: You needn't use pure json, you can use markdown or html instead for the text in order to simplify styling.)
I put together this more extensive set of samples on GitHub and you will also find details there about testing your articles with News Preview, which will help you by listing errors and so on.
Once you are ready to upload to the service you use the API having first registered to do so, examples of implementing the code are provided in Python. You can upload the article alone or a bundle containing the article and its linked files.
EDITED: Uploading an Article using Python
Copy and paste the following code into a text editor and save as upload.py
#!/usr/bin/python
import requests
import base64
from hashlib import sha256
import hmac
from datetime import datetime
import glob
import argparse
import os
import mimetypes
from requests.packages.urllib3.filepost import encode_multipart_formdata
from requests.packages.urllib3.fields import RequestField
arg_parser = argparse.ArgumentParser(description='Publish an article using the Apple News API')
arg_parser.add_argument('article_directory', metavar='ARTICLE_DIR', type=str, help='A directory containing an article.json file and resources')
args = arg_parser.parse_args()
channel_id = '[YOUR CHANNEL-ID]'
api_key_id = '[YOUR API-KEY]'
api_key_secret = '[YOUR API KEY-SECRET]'
method = 'POST'
url = 'https://news-api.apple.com/channels/%s/articles' % channel_id
session = requests.Session()
session.verify = False
def part(filename):
name = os.path.basename(filename)
with open(filename) as f:
data = f.read()
part = RequestField(name, data)
part.headers['Content-Disposition'] = 'form-data; filename="%s"; size=%d' % (name, os.stat(filename).st_size)
part.headers['Content-Type'] = 'application/json' if name.endswith('.json') else 'application/octet-stream'
return part
def send_signed_request(method, url, filenames):
body, content_type = encode_multipart_formdata([part(f) for f in filenames])
req = requests.Request(method, url, data=body, headers={'Content-Type': content_type})
req = req.prepare()
date = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
canonical_request = method + url + str(date) + content_type + body
key = base64.b64decode(api_key_secret)
hashed = hmac.new(key, canonical_request, sha256)
signature = hashed.digest().encode('base64').rstrip('\n')
authorization = 'HHMAC; key=%s; signature=%s; date=%s' % (api_key_id, str(signature), date)
req.headers['Authorization'] = authorization
return session.send(req)
response = send_signed_request(method, url, glob.glob('%s/*' % args.article_directory))
print response.status_code
print response.text
Next change the values for the following elements to your own values supplied to you by Apple:
channel_id = '[YOUR CHANNEL-ID]'
api_key_id = '[YOUR API-KEY]'
api_key_secret = '[YOUR API KEY-SECRET]'
Finally open Terminal and drag from Finder the upload.py
file you created to the command line, next leave a space before dragging in the folder containing your article.json
file so that two paths are displayed next to each other on a single line (the first being the location of the upload.py
file and the second being that of the folder containing your article.json
file). Finally press Enter.
You should see some returned JSON. Now open News Publisher inside iCloud.com and navigate to Articles > Drafts from CMS
for instructions on previewing and publishing the uploaded articles.
来源:https://stackoverflow.com/questions/43638767/how-to-upload-manipulate-apple-news-json-files