def test_post_lifecycle(self): # create a post object post = WordPressPost() post.title = 'Test post' post.slug = 'test-post' post.content = 'This is test post using the XML-RPC API.' post.comment_status = 'open' post.user = self.userid # create the post as a draft post_id = self.client.call(posts.NewPost(post)) self.assertTrue(post_id) # fetch the newly-created post post2 = self.client.call(posts.GetPost(post_id)) self.assertTrue(isinstance(post2, WordPressPost)) self.assertEqual(str(post2.id), post_id) # update the post post2.content += '<br><b>Updated:</b> This post has been updated.' post2.post_status = 'publish' response = self.client.call(posts.EditPost(post_id, post2)) self.assertTrue(response) # delete the post response = self.client.call(posts.DeletePost(post_id)) self.assertTrue(response)
def test_category_post(self): # create a test post post = WordPressPost() post.title = 'Test Post' post.slug = 'test-post' post.user = self.userid post.id = self.client.call(posts.NewPost(post)) # create a test category cat = WordPressTerm() cat.name = 'Test Category' cat.taxonomy = 'category' cat.id = self.client.call(taxonomies.NewTerm(cat)) # set category on post try: post.terms = [cat] response = self.client.call(posts.EditPost(post.id, post)) self.assertTrue(response) # fetch categories for the post to verify post2 = self.client.call(posts.GetPost(post.id, ['terms'])) post_cats = post2.terms self.assert_list_of_classes(post_cats, WordPressTerm) self.assertEqual(post_cats[0].id, cat.id) finally: # cleanup self.client.call(taxonomies.DeleteTerm(cat.taxonomy, cat.id)) self.client.call(posts.DeletePost(post.id))
def send_to_wordpress(id, title, categories, tags, content, configuration): if len(content.strip()) == 0: return client = get_client(configuration) if id: post = client.call(posts.GetPost(id)) pass else: post = WordPressPost() post.content = content if title is not None: post.title = title if post.title is None: post.title = 'My post' post.terms_names = { 'post_tag': tags, 'category': categories, } if id: client.call(posts.EditPost(post.id, post)) else: post.id = client.call(posts.NewPost(post)) print("Blog post with id " + post.id + " was successfully sent to WordPress.") return post.id
def publishPost(self, post_id): ''' publish the post with post id ''' post = self.wordpress.call(posts.GetPost(post_id)) post.post_status = 'publish' self.wordpress.call(posts.EditPost(post.id, post))
def test_revisions(self): original_title = 'Revisions test' post = WordPressPost() post.title = original_title post.slug = 'revisions-test' post.content = 'This is a test post using the XML-RPC API.' post_id = self.client.call(posts.NewPost(post)) self.assertTrue(post_id) post.title = 'Revisions test updated' post.content += ' This is a second revision.' response = self.client.call(posts.EditPost(post_id, post)) self.assertTrue(response) # test wp.getRevisions revision_list = self.client.call(posts.GetRevisions(post_id, ['post'])) self.assert_list_of_classes(revision_list, WordPressPost) # workaround for WP bug #22686/22687 # an auto-draft revision will survive wp.newPost, so pick the 2nd revision self.assertEqual(2, len(revision_list)) real_rev = revision_list[1] self.assertTrue(real_rev) self.assertNotEquals(post_id, real_rev.id) # test wp.restoreRevision response2 = self.client.call(posts.RestoreRevision(real_rev.id)) self.assertTrue(response2) post2 = self.client.call(posts.GetPost(post_id)) self.assertEquals(original_title, post2.title) # cleanup self.client.call(posts.DeletePost(post_id))
def GetPost(post_id): """Return a given post by ID.""" client = _Client() post_query = wp_posts.GetPost(post_id) try: return client.call(post_query) except xmlrpclib.Fault as e: print 'Fault getting post %s - %s' % (post_id, e) return None
def GetWebPages(): ids = [817, 819, 822, 841, 834, 836, 839, 807, 812, 1156, 1131, 847] pages = dict() client = Client(url, user, pw) for postId in ids: page = client.call(posts.GetPost(postId)) pages[page.slug] = page return pages
def __init__(self, user, password, archive, lfrom='pt', lto='pb'): client = Client('http://www.weeklyosm.eu/xmlrpc.php', user, password) post = client.call(posts.GetPost(archive)) tagfrom = '[:%s]' % lfrom tagto = '[:%s]' % lto post.title = post.title.replace(tagfrom, tagto) post.content = post.content.replace(tagfrom, tagto) #print(post.title) #print(post.content) client.call(posts.EditPost(post.id, post))
def update_post_wp(self, wp_post_id): """ Update post with id in WordPress. :param wp_post_id: post id """ post = self.client.call(posts.GetPost(wp_post_id)) if not post: raise ResourceError("Post not found, id: {}.".format(wp_post_id)) key_assoc = { "city": "city_id", "coordinates_lat": "latitude", "coordinates_long": "longitude", "geo_hash_id": "geo_hash_id", "rate": "rate", "place_id": "place_id", "address": "address_coord" } post_custom_fields = CustomFields(post.custom_fields, key_assoc) custom_fields_unpacked = post_custom_fields.unpack() try: location = [] location_unserialized = custom_fields_unpacked["city_id"] for loc in location_unserialized: term = self.client.call( taxonomies.GetTerm("locations", int(loc))) location.append(term) break except KeyError: pass db_post = self.connection.get( InterestPoint, { "latitude": custom_fields_unpacked["latitude"], "longitude": custom_fields_unpacked["longitude"] }) if not db_post: db_post = self.connection.get(InterestPoint, {"title": post.title}) if not db_post: raise MissingResourceError( "InterestPoint not found for post with id: {}.".format( post.id)) dict_post = post.__dict__() post_diff = self.prejudice_diff(post, db_post) new_post_data = WordPressPost() new_post_data.custom_fields = [] self.client.call(posts.EditPost(post.id, new_post_data)) exit()
def GetWebPages(): # the most stable way to access WordPress is to # hardcode the post IDs in here ids = [817, 819, 822, 841, 834, 836, 839, 807, 812, 1156, 1131, 847, 1428] pages = dict() client = Client(url, user, pw) for postId in ids: page = client.call(posts.GetPost(postId)) pages[page.slug] = page return pages
def delete_post(wp_post_id): user = current_user client = check_login(user.wp_url, user.wp_username, login_session['pw']) wp_post = client.call(posts.GetPost(wp_post_id)) if request.method == 'POST': client.call(posts.DeletePost(wp_post_id)) flash('Post deleted successfully') return redirect(url_for('get_posts')) else: return render_template('posts/deletepost.html', wp_post_id=wp_post_id, post=wp_post)
def __init__(self, user, password, archive): client = Client('http://www.weeklyosm.eu/xmlrpc.php', user, password) post = client.call(posts.GetPost(archive)) tag1_from = '<!--:Ja-->' tag2_from = '[:Ja]' tag1_to = '<!--:ja-->' tag2_to = '[:ja]' post.title = post.title.replace(tag1_from, tag1_to) post.title = post.title.replace(tag2_from, tag2_to) post.content = post.content.replace(tag1_from, tag1_to) post.content = post.content.replace(tag2_from, tag2_to) client.call(posts.EditPost(post.id, post))
def editPost(self, post_id, post_content, status): ''' Args: post_id: post_content: status: publish OR draft Returns: ''' post_id = 18 post = self.wordpress.call(posts.GetPost(post_id)) post.content = post_content post.post_status = status # save the change to the post self.wordpress.call(posts.EditPost(post.id, post))
def wp_post_update(request, post_id): """ Update WordPress post using Post object and HTML Primarily for 'Update This Post' button AJAX function in :view:`post_generator.views.post.post_view` :param post_id: :model:`post_generator.Post` to update WP post with :type post_id: :model:`post_generator.Post` """ # TODO: add case for GET request if request.method == 'POST': client = Client(os.environ['POSTGEN_WP_TARGET'], os.environ['POSTGEN_WP_USER'], os.environ['POSTGEN_WP_PASS']) post_obj = Post.objects.get(pk=post_id) # Generate Multilingual title post_title = post_obj.title.english if post_obj.title.somali: post_title += ' (' + post_obj.title.somali + ')' if post_obj.title.french or post_obj.title.french_feminine: post_title += ' ' + (post_obj.title.french or post_obj.title.french_feminine) if post_obj.title.arabic: post_title += ' ' + post_obj.title.arabic post_title += ' - PostGen' # Pull WP post ID from stored link matches = re.search('.*=(\d+)$', post_obj.link) wp_post_id = matches.group(1) # Create new WP post object with data wp_post = WordPressPost() wp_post.title = post_title wp_post.content = request.POST['post-content'] wp_post.date = post_obj.pub_date # Retrieve current post data via WP XML-RPC API # - Used to determine whether featured_image_id data should be included # - Avoids error from setting featured_image_id to the one already attached current_post = client.call(posts.GetPost(wp_post_id)) if not current_post.thumbnail or current_post.thumbnail[ 'attachment_id'] != str(post_obj.featured_image_id): wp_post.thumbnail = str(post_obj.featured_image_id) # Update WP post and return status=True via JSON client.call(posts.EditPost(wp_post_id, wp_post)) return HttpResponse(json.dumps({'status': True}), content_type='application/json')
def pedir_id_para_editar(): limpiar_pantalla() id_entrada_editar = int(input("Introduce el ID de la entrada que deseas editar [-1 para salir] ")) if id_entrada_editar != -1: entrada_para_editar = cliente.call(posts.GetPost(id_entrada_editar)) entrada_original = entrada_para_editar entrada_para_editar.title = input("Introduce el nuevo título: [vacío si no quieres cambiarlo] ") or entrada_original.title entrada_para_editar.content = input("Introduce el nuevo contenido: [vacío si no quieres cambiarlo] ") or entrada_original.content print("Guardando cambios...") resultado = cliente.call(posts.EditPost(id_entrada_editar, entrada_para_editar)) if resultado is True: input("Cambios guardados") else: input("Algo salió mal") imprimir_menu_opciones()
def post_article(data, title, categories): article = [] for d in data: if d.startswith('/home'): # i still dont like this add_photo(article, d) else: add_text(article, d) post = WordPressPost() post.title = title post.content = '\n'.join(article) # oof post.post_status = 'publish' post.terms_names = { 'post_tag': ['test', 'firstpost'], 'category': categories } id = wp.call(NewPost(post)) a = wp.call(posts.GetPost(id)) return a.link
def post(self): handler, post = self.make_handler_post() if 'blog' not in post: print('You need to specify which blog to post on ' 'in either brc.py or header of %s.' % handler.filename) sys.exit(1) self.auth() kind = post['kind'] title = post['title'] if kind == 'post': wpost = WordPressPost() else: wpost = WordPressPage() wpost.title = title wpost.content = post['content'] wpost.post_status = 'draft' if post['draft'] else 'publish' wpost.terms_names = { 'post_tag': post.get('labels', []), 'category': post.get('categories', []), } resp = {} if 'id' in post: print('Updating a %s: %s' % (kind, title)) self.service.call(posts.EditPost(post['id'], wpost)) else: print('Posting a new %s: %s' % (kind, title)) wpost.id = self.service.call(posts.NewPost(wpost)) wpost = self.service.call(posts.GetPost(wpost.id)) resp['id'] = wpost.id resp['url'] = wpost.link for k in ('service', 'blog', 'kind', 'draft'): resp[k] = post[k] handler.merge_header(resp) handler.write()
def wp_post_new(request): """ Create a New Post and returns the link via WordPress XML-RPC API. Populates with temporary information (updated later by :view:`post_generator.views.wordpress.wp_post_update`) """ client = Client(os.environ['POSTGEN_WP_TARGET'], os.environ['POSTGEN_WP_USER'], os.environ['POSTGEN_WP_PASS']) # Create WP post object and populate with placeholder information # - Updated later by WPPostUpdate (post_generator:wp_update) new_post = WordPressPost() new_post.title = 'New Post' new_post.content = 'New Post' new_post.id = client.call(posts.NewPost(new_post)) wp_post = client.call(posts.GetPost(new_post.id)) data = json.dumps({'link': wp_post.link}) return HttpResponse(data, content_type='application/json')
def __init__(self, user, password, archive, sync=False): """ @params archive - number in permalink like www.weeklyosm.eu/archives/4205 sync - True for downloading the brazilian version already published """ client = Client('http://www.weeklyosm.eu/xmlrpc.php', user, password) self.post = client.call(posts.GetPost(archive)) lang = 'en' if not sync else 'pt' extractor = ExtractorPosting(self.post, lang) content = extractor.do_content() markdown = html2text.html2text(content) s = markdown s = re.sub(r'^ *\*', '*', s, flags=re.MULTILINE) s = re.sub(r'([^\n]\n)\*', r'\1\n*', s, flags=re.MULTILINE) s = re.sub(r'…', '...', s) s = re.sub(r'“', '"', s) s = re.sub(r'”', '"', s) markdown = s #print(markdown) """ caption = re.findall( r'\[caption.*caption\]', markdown, flags = re.MULTILINE + re.DOTALL )[0] # TODO bug with 4639 out = re.sub(r'\n', ' ', caption) out = re.sub(r'(\(http[^\)]*) ', r'\1', out) markdown = markdown.replace(caption, out) """ self.filename = 'archive-%s.md' % archive self.markdown = markdown with open(self.filename, 'w') as text_file: text_file.write(markdown)
def test_page_parent(self): parent_page = WordPressPage() parent_page.title = 'Parent page' parent_page.content = 'This is the parent page' parent_page.id = self.client.call(posts.NewPost(parent_page)) self.assertTrue(parent_page.id) child_page = WordPressPage() child_page.title = 'Child page' child_page.content = 'This is the child page' child_page.parent_id = parent_page.id child_page.id = self.client.call(posts.NewPost(child_page)) self.assertTrue(child_page.id) # re-fetch to confirm parent_id worked child_page2 = self.client.call(posts.GetPost(child_page.id)) self.assertTrue(child_page2) self.assertEquals(child_page.parent_id, child_page2.parent_id) # cleanup self.client.call(posts.DeletePost(parent_page.id)) self.client.call(posts.DeletePost(child_page.id))
def publish_article(title, content): url = 'https://northant520.wordpress.com/' username = '******' password = '******' from urllib.parse import urljoin from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.methods import posts from wordpress_xmlrpc.exceptions import InvalidCredentialsError wp = Client(urljoin(url, 'xmlrpc.php'), username, password) wppost = WordPressPost() wppost.title = title wppost.content = content wppost.post_status = 'publish' try: id = wp.call(posts.NewPost(wppost)) except InvalidCredentialsError: raise Exception('账户名或密码错误') url = wp.call(posts.GetPost(id)).link diigo = Diigo() diigo.publish(url, title)
def test_page_lifecycle(self): page = WordPressPage() page.title = 'Test Page' page.content = 'This is my test page.' # create the page page_id = self.client.call(posts.NewPost(page)) self.assertTrue(page_id) # fetch the newly created page page2 = self.client.call( posts.GetPost(page_id, results_class=WordPressPage)) self.assertTrue(isinstance(page2, WordPressPage)) self.assertEqual(str(page2.id), page_id) # edit the page page2.content += '<br><b>Updated:</b> This page has been updated.' response = self.client.call(posts.EditPost(page_id, page2)) self.assertTrue(response) # delete the page response = self.client.call(posts.DeletePost(page_id)) self.assertTrue(response)
def test_get_post(user, password, archive): client = Client('http://www.weeklyosm.eu/xmlrpc.php', user, password) post = client.call(posts.GetPost(archive)) print(post.title)
post_category_id = 0 for val in taxes: if str(val) == str(industry): is_present = 1 post_category_id = val.id break if is_present == 0: tag = WordPressTerm() tag.taxonomy = 'company_category' tag.name = industry post_category_id = wp.call(taxonomies.NewTerm(tag)) category = wp.call(taxonomies.GetTerm('company_category', post_category_id)) post = wp.call(posts.GetPost(new_company.id)) post.terms.append(category) wp.call(posts.EditPost(post.id, post)) attachment_id = 0 if logo: print "https://www.mustakbil.com"+str(logo) img_data = requests.get("https://www.mustakbil.com"+str(logo)).content with open('file01.jpg', 'wb') as handler: handler.write(img_data)
def GetPost(post_id=None, optional_args=None): return Bj.WpCli.call( posts.GetPost(post_id))
for val in taxes: if str(val) == str(type): is_present = 1 post_category_id = val.id break if is_present == 0: tag = WordPressTerm() tag.taxonomy = 'job_listing_type' tag.name = type post_category_id = wp.call(taxonomies.NewTerm(tag)) category = wp.call( taxonomies.GetTerm('job_listing_type', post_category_id)) post = wp.call(posts.GetPost(new_job.id)) post.terms.append(category) wp.call(posts.EditPost(post.id, post)) attachment_id = 0 if logo: print "https://www.mustakbil.com" + str(logo) img_data = requests.get("https://www.mustakbil.com" + str(logo)).content with open('file01.jpg', 'wb') as handler: handler.write(img_data)
def view_post(post_id): user = current_user client = check_login(user.wp_url, user.wp_username, login_session['pw']) wp_post = client.call(posts.GetPost(post_id)) return render_template('posts/post.html', post=wp_post)
def get_post(): p = wp_clt.call(posts.GetPost(142)) print type(p), p print p.comment_status
def get_post(self, post_id): """Wrapper for invoking the GetPost method.""" return self._wp.call(posts.GetPost(post_id))
client = Client("http://www.alaya.moe/xmlrpc.php", "WordPressUserName", "WordPressPassword") #上传二维码 data = { 'name': 'qrcode' + nowtime.strftime('%Y-%m-%d') + '.jpg', 'type': 'image/jpeg', # mimetype } with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = client.call(media.UploadFile(data)) #更新wordpress文章 post = client.call(posts.GetPost(171)) post.title = '科学上网账号(' + nowtime.strftime('%Y-%m-%d %H') + '点更新)' pattern = '服务器端口:(\d+)' replacetext = '服务器端口:' + randomnum post.content = re.sub(pattern, replacetext, post.content) pattern = '最新更新时间:([\d -/:]+)' replacetext = '最新更新时间: ' + nowtime.strftime('%Y-%m-%d %H:%M:%S') post.content = re.sub(pattern, replacetext, post.content) # 更新快捷导入 pattern = "\[<img src=\"http://www.alaya.moe/wp-content/uploads/2017/03/import.png\"/>\]\((.+)\)" replacetext = "[<img src=\"http://www.alaya.moe/wp-content/uploads/2017/03/import.png\"/>](" + shareqrcode_str + ")" post.content = re.sub(pattern, replacetext, post.content)