예제 #1
0
파일: mks.py 프로젝트: fccn/nau-wp-sync
    def getClient(self):

        if not self._connection:
            self._connection = Client(self.url(), self.settings["username"],
                                      self.settings["password"])

        return self._connection
예제 #2
0
def wpsend(content, title, vido_info_kind):
    try:
        # 链接地址,登录用户名,密码
        wp = Client('http://192.168.190.145/xmlrpc.php', 'bruce', '12345678')
        # print(content)
        post = WordPressPost()
        # 设置标题内容
        post.title = str(title)
        # 文章正文内容
        post.content = " ''' " + content + " ''' "
        # 可见性,publish:全部可见;
        post.post_status = 'publish'
        # 设置标签,分类
        post.terms_names = {
            'post_tag': ['影视'],
            'category': ['影视', '链接资源', vido_info_kind]
        }
        # 验证是否有相同标题
        old_post = wp.call(GetPost(post.title))
        # old_post = GetPost(post.title)
        print(old_post)
        if post.title == old_post:
            wp.call(DeletePost(post.title))
            print('已经删除{}'.format(post.title))
        else:
            # 新建文章
            wp.call(NewPost(post))
            localtime = time.localtime(time.time())
            print('文档已上传 {}'.format(
                time.strftime("%Y-%m-%d %H:%M:%S", localtime)))
    except:
        print('没有上传成功')
예제 #3
0
    def load_file(self):
        fname = askopenfilename(filetypes=(("PNG Image", "*.png"),
                                           ("JPG Image", "*.jpg;*.jpeg"),
                                           ("GIF Image", "*.gif"),
                                           ("Bitmap Image",
                                            "*.bmp"), ("All Files", "*")))
        print(mimetypes.guess_type(fname)[0])
        try:
            wp = Client('https://your.wordpress.installation/xmlrpc.php',
                        'Username', 'password')
        except TimeoutError:
            self.status.delete(0, END)
            self.status.insert(0, 'Unable to connect to WP')
        except gaierror:
            self.status.config(state=NORMAL)
            self.status.delete(1.0, END)
            self.status.insert(1.0, 'DNS lookup failed')
            self.status.config(state=DISABLED)
            raise

        print(MyFrame.path_leaf(fname))
        data = {
            'name': MyFrame.path_leaf(fname),
            'type': mimetypes.guess_type(fname)[0]
        }
        with open(fname, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
        print(response['url'])
        self.status.config(state=NORMAL)
        self.status.delete(1.0, END)
        self.status.insert(1.0, 'Link: ' + response['url'])
        self.status.config(state=DISABLED)
예제 #4
0
def sent_to_wp(title, content):
    #prepare metadata
    # data = {
    #         'name': filename,
    #         'type': 'image/jpeg',  # mimetype
    # }
    #
    # # read the binary file and let the XMLRPC library encode it into base64
    wp = Client('http://abc/xmlrpc.php', 'link', '!@#abc')
    if wp:
        print('wp link ok')
    else:
        print('wp link false')

    # sent_to_wp(title,content)
    # with open(fullname, 'rb') as img:
    #         data['bits'] = xmlrpc_client.Binary(img.read())
    # response = wp.call(media.UploadFile(data))
    # #print('response: %s' % response)
    # attachment_id = response['id']
    #print('attachment_id: %s %s' %(type(attachment_id),attachment_id))

    post = WordPressPost()
    post.title = title
    post.content = content
    post.post_status = 'publish'
    #post.thumbnail = attachment_id
    post.id = wp.call(posts.NewPost(post))
    print('title:%s  =>post success' % title)
    print(
        '-----------------------------------------------------------------------------------------------'
    )
    def isValid(self, credentials):
        
        """ 
       
        Validates Credentials.
        -------              
      
        This function uses the Credentials as parameter to call the Client Class, which 
        is the gateway to the CMS XML-RPC interface. The Client class validates the Credentials.
        -------              
      
        Parameters: 
        -------              
        credentials (Credentials) : Credentials that will be validated          
      
        
        Returns: 
        -------              
        cms (Client) : the CMS XML-RPC interface
       
       """ 

        self.cms = Client(URL, credentials['user'], credentials['password'])

        return self.cms
def showText():
    title = title_entry.get()
    description = description_entry.get('1.0', END)

    isYes = messagebox.askyesno("Confirmation to post",
                                "Are you sure you want to post?")
    if isYes:
        print("Title: {titleKey} \nDescrption: {descriptionKey}".format(
            titleKey=title, descriptionKey=description))
        wp = Client('https://vijayatm.wordpress.com/xmlrpc.php',
                    'yourUserName',
                    'yourPassword')  #replace your username and password here
        data = {'name': 'Python file Name.jpg', 'type': 'image/jpg'}
        with open(imgArg, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
        attachmentURL = response['url']
        attachmentID = response['attachment_id']
        print(response)

        post = WordPressPost()
        post.title = title
        post.content = "<img src='{att1}'/><br>{description}".format(
            att1=attachmentURL, description=description)
        post.thumbnail = attachmentID
        post.terms_names = {
            'post_tag': ['vijayatm', 'usingPython', 'tkinter', 'wordpress']
        }
        post.post_status = 'publish'
        resp = wp.call(NewPost(post))
        print(resp)
        root.destroy()
    else:
        messagebox.showinfo('Welcome Back',
                            'Update the description if you want to')
def sends():
    print len(targeturl)
    for i in range(len(targeturl)):
        #u=content1[i][0]
        url = "http://whuhan2013.github.io" + targeturl[i]
        print url
        a = Article(url, language='zh')
        a.download()
        a.parse()
        title = a.title
        dst = a.text

        #链接WordPress,输入xmlrpc链接,后台账号密码
        wp = Client('http://127.0.0.1:22222/xmlrpc.php', 'www', '!abc6')
        #示例:wp = Client('http://www.python-cn.com/xmlrpc.php','username','password')
        post = WordPressPost()
        post.title = title
        #post.post_type='test'
        #post.content = dst
        post.description = dst
        post.post_status = 'publish'
        #发送到WordPress
        wp.call(NewPost(post, True))
        time.sleep(3)
        print 'posts updates'
예제 #8
0
def upload_audio_to_wordpress(config, audio_path):
    """uploads the audio to wordpress using the credentials stored in config"""
    import mimetypes
    from wordpress_xmlrpc import Client
    from wordpress_xmlrpc.compat import xmlrpc_client
    from wordpress_xmlrpc.methods import media

    wordpress_handle = Client(config["wordpress"]["url"] + "/xmlrpc.php",
                              config["wordpress"]["user"],
                              config["wordpress"]["password"])

    audio_name = audio_path.split("/")[-1]

    audio_mime_type = mimetypes.guess_type(audio_path)
    # prepare metadata
    data = {
        'name': audio_name,
        'type': audio_mime_type,
    }

    # read the binary file and let the XMLRPC library encode it into base64
    with open(audio_path, 'rb') as audio_data:
        data['bits'] = xmlrpc_client.Binary(audio_data.read())

    response = wordpress_handle.call(media.UploadFile(data))

    return response['url']
예제 #9
0
def get_post(request, id):
    wordpress_settings = get_wordpress_meta()
    wp = Client(wordpress_settings["rpc"], wordpress_settings["username"],
                wordpress_settings["password"])
    post = wp.call(GetPost(id))
    serializer = PostSerializer(post)
    return Response(serializer.data)
예제 #10
0
def wordpress_artice(wppost_status, wp_title, wp_slug_title, wp_content,
                     wp_category, wp_post_tag, wp_host, wp_user, wp_password):
    # 如果遇到错误就出试5次
    success_num = 0
    while success_num < 5:
        try:
            client = Client(wp_host, wp_user, wp_password)

            newpost = WordPressPost()  # 创建一个类实例,注意,它不是一个函数。只要在一个类名后面加上括号就是一个实例
            # newpost.post_status = 'draft'
            newpost.post_status = wppost_status
            newpost.slug = wp_slug_title  # 文章别名,固定链接形式为文章标题时需要
            # 设置发布目录(一篇文章可以属于多个分类目录)
            newpost.terms_names = {
                'category': wp_category,  # 目录
                'post_tag': wp_post_tag  # 标签
            }
            newpost.title = wp_title
            newpost.content = wp_content
            client.call(posts.NewPost(newpost))  #发布新建的文章,返回的是文章id
            print("Wordpress发布成功:", wp_title)

        except Exception as e:
            print("正在重试:", e)
            success_num = success_num + 1
            continue
예제 #11
0
def postNewPostByXmlRpc(title, content, enterName, techField, techMaturity,
                        contactName, contactTel, contactEmail, completeDate,
                        applyStatus, cowork_type, apply_score, result_type,
                        award_type, award_level, prospect_promotion,
                        patent_name, postal_address, district, images, prov):
    print("postNewPostByXmlRpc")
    wp = Client('http://39.106.104.45/wordpress/xmlrpc.php', 'shikun',
                'ShiKun001')
    post = WordPressPost()
    post.title = title
    post.content = gen_content(content, enterName, applyStatus, apply_score,
                               result_type, award_type, award_level,
                               prospect_promotion, patent_name, postal_address,
                               images)
    post.terms_names = {
        'category': ['成果展示']
    }
    #post.custom_fields = {
    #    'enter-name':enterName,
    #    'tech-field': techField,
    #    'tech-maturity': techMaturity,
    #    'contact-name':contactName,
    #    'contact-tel':contactTel,
    #    'contact-email':contactEmail
    #};
    post.id = wp.call(NewPost(post))
    print("post.id = " + str(post.id))
    postId = post.id
    insertOtherDataIntoDB(postId, enterName, techField, techMaturity,
                          contactName, contactTel, contactEmail, completeDate,
                          cowork_type, district)

    insertProvDataIntoDB(postId, prov, enterName)
    savePostId(postId)
예제 #12
0
    def UploadFile(self):
        url = self.targetUrl + '/xmlrpc.php'
        client = Client(url, self.atLeastAuthorAccount['log'],
                        self.atLeastAuthorAccount['pwd'])
        # set to the path to your file
        filepath = self.fileToUpload['filepath']

        # prepare metadata
        data = {
            'name': self.fileToUpload['filename'],
            'type': 'image/jpeg',  # mimetype
        }

        # read the binary file and let the XMLRPC library encode it into base64
        with open(filepath, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())

        response = client.call(media.UploadFile(data))
        # response == {
        #       'id': 6,
        #       'file': 'picture.jpg'
        #       'url': 'http://www.example.com/wp-content/uploads/2012/04/16/picture.jpg',
        #       'type': 'image/jpeg',
        # }
        print("Uplaod ảnh nhiễm độc thành công!")
        return response
예제 #13
0
    def setUp(self):
        wp = Client('http://lightcastletech.wordpress.com/xmlrpc.php',
                    '*****@*****.**', settings.WORDPRESS_PASS)
        self.all_posts = wp.call(
            GetPosts({
                'number': 100,
                'post_status': 'publish'
            }))
        self.authors = wp.call(GetAuthors())
        self.all_posts = self.all_posts[::
                                        -1]  #reverse the list of posts so that the most recent are last in the list
        for post in self.all_posts:
            for author in self.authors:
                if author.id == post.user:
                    post.author = author.display_name
#          following line sets the image variable so the posts index can display right
            if blog._get_first_image(post.content) != "None":
                post.image = blog._get_first_image(post.content)
            else:
                post.image = ""

            b = blog.Blog(title=post.title,
                          author=post.author,
                          initial_image=post.image,
                          date=post.date,
                          content=post.content)
            b.save()
예제 #14
0
def wpClient():
    '''
    Base class used to connect to Wordpress via XMLRPC.
    '''
    return Client(settings.WORDPRESS_MIGRATR['server'],
                  settings.WORDPRESS_MIGRATR['user'],
                  settings.WORDPRESS_MIGRATR['pass'])
def sent_to_wp(filename,fullname,title,content):
    #prepare metadata
    data = {
            'name': filename,
            'type': 'image/jpeg',  # mimetype
    }
    #
    # # read the binary file and let the XMLRPC library encode it into base64
    wp = Client('http://www.abc.cn/xmlrpc.php', 'www', 'abc16')
    # sent_to_wp(title,content)
    with open(fullname, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
    response = wp.call(media.UploadFile(data))
    #print('response: %s' % response)
    attachment_id = response['id']
    #print('attachment_id: %s %s' %(type(attachment_id),attachment_id))

    post = WordPressPost()
    post.title = title
    post.content = content
    post.post_status = 'publish'
    post.thumbnail = attachment_id
    post.id = wp.call(posts.NewPost(post))
    print('title:%s  =>post success' % title)
    print('-----------------------------------------------------------------------------------')
예제 #16
0
def post(wp_url, wp_user, wp_pw, wp_title, wp_context, wp_thumbnail, wp_tags,
         wp_categorys):
    while True:
        try:
            client = Client(wp_url, wp_user, wp_pw)
            if wp_thumbnail != None:
                filename = wp_thumbnail
                # prepare metadata
                data = {
                    'name': 'picture.jpg',
                    'type': 'image/jpeg',  # mimetype
                }

                # read the binary file and let the XMLRPC library encode it into base64
                with open(filename, 'rb') as img:
                    data['bits'] = xmlrpc_client.Binary(img.read())

                response = client.call(media.UploadFile(data))
                attachment_id = response['id']
            post = WordPressPost()
            post.title = wp_title
            post.content = wp_context
            post.post_status = 'publish'
            if wp_thumbnail != None:
                post.thumbnail = attachment_id
            post.terms_names = {'post_tag': wp_tags, 'category': wp_categorys}
            post.id = client.call(posts.NewPost(post))
            return "https://weporn.tv/?p=" + str(post.id)
        except:
            pass
예제 #17
0
    def detail_page(self, response):
        title = response.doc('h1').text(),
        texts = str(response.doc('.loadimg.fadeInUp > p'))  #获取所有的HTML标签和内容
        texts = texts.replace("https://www.ttfhvip.com/d/file", "/downimages")
        texts = texts.replace("下面我们一起来看看她最新的番号作品吧!", "")
        texts = texts.replace("点击查看更多番号作品", "")

        for each in response.doc('.loadimg.fadeInUp > p > img').items():
            img_url = each.attr.src
            if ("ttfhvip" in img_url):  #过滤掉不在ttfhvip站点上的图片连接
                split_url = img_url.split('/')
                dir_name = split_url[-2] + '/'
                dir_path = self.deal.mkDir(dir_name)
                file_name = split_url[-1]
                self.crawl(img_url,
                           callback=self.save_img,
                           save={
                               'dir_path': dir_path,
                               'file_name': file_name
                           })
        title = ''.join(str(title))
        title = title.replace("('", "")
        title = title.replace("',)", "")
        wp = Client('http://192.168.2.98/xmlrpc.php', '东京不热郎', 'qaz78963')
        post = WordPressPost()
        post.title = title
        post.content = texts
        post.post_status = 'draft'  #publish-发布,draft-草稿,private-私密
        post.terms_names = {
            'category': ['素人']  #文章所属分类,没有则自动创建
        }
        post.id = wp.call(posts.NewPost(post))
예제 #18
0
def main():
    (options, args) = parse_options()

    #
    # Check if the file exists
    #
    if not os.path.exists(args[0]):
        print("File:%s does not exists, aborting!" % args[0])
        sys.exit(1)

    new_post_file = open(args[0], 'r')
    new_post_content = new_post_file.read()
    new_post_file.close()

    client = Client('http://192.168.50.50/xmlrpc.php', 'tony',
                    'tony_wordpress_123')

    now = datetime.datetime.now()

    post = WordPressPost()
    post.title = 'My New Post - %s' % now.strftime("%Y-%m-%d_%H_%M_%S")
    post.content = new_post_content
    post.id = client.call(posts.NewPost(post))

    post.post_status = 'publish'
    client.call(posts.EditPost(post.id, post))
예제 #19
0
    def createPost(self, title, description, size, tags, links, category):
        wp = Client(self.wp_url,
                    self.wp_username,
                    self.wp_password,
                    transport=SpecialTransport())
        post = WordPressPost()
        post.post_status = 'publish'
        title = title.replace('.', ' ')
        title = title.replace('_', ' ')
        post.title = title
        post.content = 'Size:<b> ' + size + '</b> <br /><br /><br />'
        post.content = post.content + description
        post.content = post.content + '<br /><div class=' "downLinks" '>Download Links:</div>'

        addLinks = '<textarea readonly>'
        for link in links:
            addLinks = addLinks + link + '&#13;&#10;'
        addLinks = addLinks + '</textarea>'

        post.content = post.content + addLinks

        post.terms_names = {'post_tag': tags, 'category': [category]}

        id = wp.call(NewPost(post))
        postLink = WordPressPost()
        postLink = wp.call(GetPost(id))
        return postLink.link
예제 #20
0
 def __init__(self, url: str, username: str, password: str) -> None:
     self._client: Client = Client(url='{}/xmlrpc.php'.format(url),
                                   username=username,
                                   password=password)
     self._api: WordpressAPI = WordpressAPI(url=url,
                                            username=username,
                                            password=password)
예제 #21
0
    def post_article(self, wpUrl, wpUserName, wpPassword, articleCategories,
                     path):
        self.path = path
        self.wpUrl = wpUrl
        self.wpUserName = wpUserName
        self.wpPassword = wpPassword

        client = Client(self.wpUrl, self.wpUserName, self.wpPassword)
        filename = self.path

        try:
            myFile = open(filename, "r")
            rawText = myFile.read()
            rawText = rawText.decode('latin-1')
            myFile.close()
            articleTitle = remove_tags(rawText)
            articleContent = rawText
            post = WordPressPost()
            post.title = articleTitle[:90]
            post.content = articleContent
            post.terms_names = {'category': articleCategories}
            post.post_status = 'publish'
            post.mime_type = "text/html"
            post.id = client.call(posts.NewPost(post))
            print("success : " + os.path.basename(path))
            os.remove(path)
        except (Exception, e):
            print("error : " + os.path.basename(path))
            print(e)
예제 #22
0
def wpsend(content, title, vido_info_kind):
    try:
        # 链接地址,登录用户名,密码
        wp = Client('http://magnetkey.xyz/xmlrpc.php', 'bruce',
                    'flzx3qc@ysyhl9t')
        # wp = Client('http://192.168.190.145/xmlrpc.php', 'bruce', '12345678')
        # print(content)
        post = WordPressPost()
        # 设置标题内容
        post.title = str(title)
        # 文章正文内容
        post.content = " ''' " + content + " ''' "
        # 可见性,publish:全部可见;'private':私有
        post.post_status = 'publish'
        # 设置标签,分类
        post.terms_names = {
            'post_tag': ['影视'],
            'category': ['影视', '在线播放资源', vido_info_kind]
        }
        # # 新建文章
        wp.call(NewPost(post))
        localtime = time.localtime(time.time())
        print('文档已上传 {}'.format(time.strftime("%Y-%m-%d %H:%M:%S", localtime)))
    except:
        print('没有上传成功')
예제 #23
0
def make_post(content):
    wp = Client('https://yoursite.com/xmlrpc.php', 'user', 'pass')
    post = WordPressPost()
    post.title = content['title']
    post.content = content['body']
    post.terms_names = {
        'post_tag': ['AutoBlogger', 'BotPosted'],
        'category': ['News', 'Update']
    }
    # Lets Now Check How To Upload Media Files
    filename = '1.jpg'
    data = {
        'name': '1.jpg',
        'type': 'image/jpeg'  # Media Type
    }
    # Now We Have To Read Image From Our Local Directory !
    with open(filename, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
    attachment_id = response['id']

    # Above Code Just Uploads The Image To Our Gallery
    # For Adding It In Our Main Post We Need To Save Attachment ID
    post.thumbnail = attachment_id
    post.post_status = 'publish'
    post.id = wp.call(posts.NewPost(post))
    # Set Default Status For Post .i.e Publish Default Is Draft

    # We Are Done With This Part :) Lets Try To Run It
    print("Sucessfully Posted To Our Blog !")
예제 #24
0
def main():
    p = argparse.ArgumentParser(
        description='Create an embeddable page for Arsenalist videos')
    p.add_argument('-u', '--username', required=True)
    p.add_argument('-p', '--password', required=True)
    args = vars(p.parse_args())
    username = args['username']
    password = args['password']

    wp = Client('https://arsenalist.com/xmlrpc.php', username, password)
    posts = wp.call(GetPosts())
    bits = []
    for p in posts:
        custom_fields = p.custom_fields
        for cf in custom_fields:
            if cf['key'] == 'gallery_json':
                raw = json.loads(cf['value'])
                raw = raw[::-1]
                for r in raw:
                    if 'sort' not in r:
                        r['sort'] = 0
                raw = sorted(raw, key=lambda item: item['sort'], reverse=True)
                bits.extend(raw)

    print(create_embed(bits))
예제 #25
0
def PushToWeb(courses):
    if not pushToWordPress:
        return
    client = Client(url, user, pw)
    pages = GetWebPages()

    for course in courses:
        print("pushing to web", course)
        try:
            page = pages[course]
            f = open("raw/%s.html" % (course, ), "r")
            page.content = f.read()
            f.close()
        except IOError as ioe:
            print("** no raw file found for", course)
            print(ioe)
            continue
        except KeyError as keyx:
            print("** no course found on blog", course)
            print(keyx)
            continue

        result = client.call(posts.EditPost(page.id, page))
        if result:
            print("Successfully updated ", page.slug)
        else:
            print("******Warning********: could not update ", page.slug)
예제 #26
0
 def _create_connection(self, parsed_args):
     try:
         self.wp = Client(self.xmlrpc_url, self.username, self.password)
     except self._WP_FAILURE_MODES as err:
         self.LOG.error('Could not connect to %s' % self.xmlrpc_url)
         self.LOG.error('Bad site/url or XML-RPC  is not enabled: %s' % err)
         raise
예제 #27
0
 def readfromclipboard(self):
     temporarybuffer = io.BytesIO()
     ImageGrab.grabclipboard().save(temporarybuffer, format='png')
     ##        temporarybuffer.seek(0,2)
     ##        print(temporarybuffer.tell())
     try:
         wp = Client('https://your.wordpress.installation/xmlrpc.php',
                     'Username', 'password')
     except TimeoutError:
         self.status.delete(0, END)
         self.status.insert(0, 'Unable to connect to WP')
     except gaierror:
         self.status.config(state=NORMAL)
         self.status.delete(1.0, END)
         self.status.insert(1.0, 'DNS lookup failed')
         self.status.config(state=DISABLED)
         raise
     data = {
         'name':
         ''.join(
             random.choice(
                 '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
             ) for i in range(16)) + '.png',
         'type':
         'image/png'
     }
     data['bits'] = xmlrpc_client.Binary(temporarybuffer.getvalue())
     response = wp.call(media.UploadFile(data))
     print(response['url'])
     self.status.config(state=NORMAL)
     self.status.delete(1.0, END)
     self.status.insert(1.0, 'Link: ' + response['url'])
     self.status.config(state=DISABLED)
예제 #28
0
파일: final.py 프로젝트: paul359/practice
	def post_article(self,wpUrl,wpUserName,wpPassword,articleTitle, articleCategories, articleContent, articleTags,PhotoUrl):
		self.path=os.getcwd()+"/00000001.jpg"
		self.articlePhotoUrl=PhotoUrl
		self.wpUrl=wpUrl
		self.wpUserName=wpUserName
		self.wpPassword=wpPassword
		#Download File
		f = open(self.path,'wb')
		f.write(urllib.urlopen(self.articlePhotoUrl).read())
		f.close()
		#Upload to WordPress
		client = Client(self.wpUrl,self.wpUserName,self.wpPassword)
		filename = self.path
		# prepare metadata
		data = {'name': 'picture.jpg','type': 'image/jpg',}
		
		# read the binary file and let the XMLRPC library encode it into base64
		with open(filename, 'rb') as img:
			data['bits'] = xmlrpc_client.Binary(img.read())
		response = client.call(media.UploadFile(data))
		attachment_id = response['id']
		#Post
		post = WordPressPost()
		post.title = articleTitle
		post.content = articleContent
		post.terms_names = { 'post_tag': articleTags,'category': articleCategories}
		post.post_status = 'publish'
		post.thumbnail = attachment_id
		post.id = client.call(posts.NewPost(post))
		print 'Post Successfully posted. Its Id is: ',post.id
def postToWP(title, article, url_bing):
    request = urllib2.Request(url_bing)
    request.add_header('Authorization', credentialBing)
    requestOpener = urllib2.build_opener()
    response = requestOpener.open(request)
    results = json.load(response)
    l = len(results['d']['results'])
    image = results['d']['results'][random.randint(0,l-1)]['Thumbnail']['MediaUrl']
    response = requests.get(image, stream=True)
    with open('image'+h+m+s+'.jpg', 'wb') as out_file:
        shutil.copyfileobj(response.raw, out_file)
    del response
    filename = 'image'+h+m+s+'.jpg'
    url = 'http://www.'+args.profile+'.com/xmlrpc.php'
    wp = Client(url, 'admin', 'wIn$j5vG$#NryzJGGlBMd20J')
    # prepare metadata
    data = {
        'name': 'image'+h+m+s+'.jpg',
        'type': 'image/jpeg',  # mimetype
    }
    with open(filename, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
    response = wp.call(media.UploadFile(data))
    
    img = '/wp-content/uploads/'+yr+'/'+mo+'/image'+h+m+s+'.jpg'
    post = WordPressPost()
    post.title = title
    post.content = '<img class="alignleft" src="'+img+'" width="341" height="341"/> \n' + article
    post.terms_names = {
        'category': categories[:2]
    }
    
    post.post_status = 'publish'
    wp.call(NewPost(post))
    return True
예제 #30
0
def wordpress_background_task(api):
    log("IOT background task")

    data1= "{"
    for key1, value in cbpi.cache.get("sensors").iteritems():
        data1 += ", " if key1 >1 else ""
        data1 += "\"%s\":%s" % (value.name, value.instance.last_value)
    data1 += "}"
    
    data2= "{"
    for key2, value2 in cbpi.cache.get("actors").iteritems():
        data2 += ", " if key2 >1 else ""
        data2 += "\"%s\":%s,%s" % (value2.name, value2.state, value2.power)
    data2 += "}"
    
    log("Wordpress Update")
    
    blog = Client(Wordpress_Domain + "xmlrpc.php", Wordpress_Username, Wordpress_Password)
    post = WordPressPost()
    # Create a title with some simple styling classes
    post.title = time.strftime("%y/%m/%d %H:%M:%S", time.localtime())
    post.content = data1 + "<br />" + data2
    post.terms_names = {
            'post_tag': [Wordpress_Tag],
            'category': [Wordpress_Category],
    }
    post.id = blog.call(posts.NewPost(post))
    # Always publish these posts
    post.post_status = 'publish'
    blog.call(posts.EditPost(post.id, post))