Guest User

Untitled

a guest
Mar 17th, 2018
771
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. import json
  2. import sys
  3. import urllib2
  4. from lxml import etree
  5. import httplib
  6. httplib.HTTPConnection._http_vsn = 10
  7. httplib.HTTPConnection._http_vsn_str = 'HTTP/1.0'
  8.  
  9. response = urllib2.urlopen('http://www.beyondliteracy.com/wp-json/wp/v2/posts')
  10. posts = json.loads(response.read())
  11. for post in posts:
  12. print(' - Post ID: {0}, Title: {1}, Url: {2}'
  13. .format(post['id'], post['title']['rendered'], post['link']))
  14.  
  15.  
  16. def update_post(api_base, post_id, post_content):
  17. # more than just the content field can be updated. see the api docs here:
  18. # https://developer.wordpress.org/rest-api/reference/posts/#update-a-post
  19. data = json.dumps({
  20. 'content': post_content
  21. })
  22.  
  23. url = api_base + 'wp/v2/posts/{post_id}/?id={post_id}abc'.format(post_id=post_id)
  24. req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
  25. response = urllib2.urlopen(req).read()
  26.  
  27. print('* Post updated. Check it out at {0}'.format(json.loads(response)['link']))
  28.  
  29.  
  30. def print_usage():
  31. print('Usage: {0} <url> (optional: <post_id> <file with post_content>)'.format(__file__))
  32.  
  33.  
  34. if __name__ == '__main__':
  35.  
  36. # ensure we have at least a url
  37. if len(sys.argv) < 2:
  38. print_usage()
  39. sys.exit(1)
  40.  
  41. # if we have a post id, we need content too
  42. if 2 < len(sys.argv) < 4:
  43. print('Please provide a file with post content with a post id')
  44. print_usage()
  45. sys.exit(1)
  46.  
  47. print('* Discovering API Endpoint')
  48. api_url = sys.argv[1]
  49. print('* API lives at: {0}'.format(api_url))
  50.  
  51. # if we only have a url, show the posts we have have
  52. if len(sys.argv) < 3:
  53. print('* Getting available posts')
  54.  
  55. sys.exit(0)
  56.  
  57. # if we get here, we have what we need to update a post!
  58. print('* Updating post {0}'.format(sys.argv[2]))
  59. with open(sys.argv[3], 'r') as content:
  60. new_content = content.readlines()
  61.  
  62. update_post(api_url, sys.argv[2], ''.join(new_content))
  63.  
  64. print('* Update complete!')
Add Comment
Please, Sign In to add comment