Example #1
0
def testUpdate(pid):
    client = initClient()
    post = WordPressPost()
    post.title = 'My new title update 2'
    post.content = 'This is the body of my new post.'
    post.slug= 'helloword'
    post.post_type = 'post'
    post.post_status = 'draft'
    print client.call(posts.EditPost(pid, post))
def process_comment(wp, video_id, parent_post_id, comment):
    post = WordPressPost()
    post.title = comment['text'][6:50]
    post.content = get_post_content(video_id,comment)
    post.post_type = 'video-highlight'
    post.post_status = 'publish'
    post.parent_id = parent_post_id
    #logger.info("Created post with ID [%s]", wp.call(NewPost(post)))
    print "Created post with ID [%s]" % wp.call(NewPost(post))
Example #3
0
def testUpdate(pid):
    client = initClient()
    post = WordPressPost()
    post.title = 'My new title update 2'
    post.content = 'This is the body of my new post.'
    post.slug = 'helloword'
    post.post_type = 'post'
    post.post_status = 'draft'
    print client.call(posts.EditPost(pid, post))
Example #4
0
def makeWpPost(prod_title, description, attachment_id):
    post = WordPressPost()
    post.title = prod_title
    post.content = description
    post.post_type = "product"
    post.post_status = "draft"
    post.thumbnail = attachment_id
    addpost = client.call(posts.NewPost(post))
    print 'Product added: ' + prod_title
    print '\n'
def sourcename(url, cat1=None, cat2=None, cat3=None, d=True):
    html = getPage(url, "page1.html")
    os.remove('pages/page1.html')
    title = html.select('h1')[0].text
    first_para = html.select('.story-content > p:nth-of-type(1)')[0].text
    second_para = html.select('.story-content > p:nth-of-type(2)')[0].text
    try:
        image = html.select('.image > img')[0].get('src')
    except Exception:
        image = None
    wp = Client('http://www.domain.com/xml-rpc.php', 'username', 'password')
    if image:
        filename = 'http://www.livemint.com' + image
        path = os.getcwd() + "\\00000001.jpg"
        f = open(path, 'wb')
        f.write(urllib.urlopen(filename).read())
        f.close()
        # prepare metadata
        data = {
            'name': 'picture.jpeg',
            'type': 'image/jpeg',  # mimetype
        }

        with open(path, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
    post = WordPressPost()
    post.title = title
    post.user = 14
    post.post_type = "post"
    post.content = first_para + '\n' + '\n' + second_para
    if d:
        post.post_status = "draft"
    else:
        post.post_status = "publish"
    if image:
        attachment_id = response['id']
        post.thumbnail = attachment_id
    post.custom_fields = []
    post.custom_fields.append({
        'key': 'custom_source_url',
        'value': url
    })
    if cat1:
        cat1 = wp.call(taxonomies.GetTerm('category', cat1))
        post.terms.append(cat1)
    if cat2:
        cat2 = wp.call(taxonomies.GetTerm('category', cat2))
        post.terms.append(cat2)
    if cat3:
        cat3 = wp.call(taxonomies.GetTerm('category', cat3))
        post.terms.append(cat3)
    addpost = wp.call(posts.NewPost(post))
def import_application(data):
    """
    Creates an Application post from a spreadsheet row.

    :param data: Dict of imported row from csv via DictReader
    :return:
    """
    for app in data:
        post = WordPressPost()
        post.post_status = 'publish'
        post.title = app['Application'].strip()
        post.slug = slugify(post.title)
        post.post_type = 'apps'

        # Compile post body
        content = html_format(app['Description'])
        if app['CCX']:
            content += html_format('CCX Page:' + app['CCX'])
        if app['Website']:
            content += html_format('Website: ' + app['Website'])
        if app['POC']:
            content += html_format('Contact: ' + app['POC'])
        if content:
            post.content = content

        terms = {}
        # Community terms
        community = []
        if app['SGC']:
            community.append(app['SGC'])
        if community:
            terms['communities'] = community

        # Status Terms
        status = []
        if app['Status']:
            status.append(app['Status'])
        if app['Sharing'] == 'Shareable':
            status.append(app['Sharing'])
        if status:
            terms['status'] = status

        # General Tags
        tags = []
        if app['Priority Area']:
            tags.append(app['Priority Area'])
        if tags:
            terms['post_tag'] = tags

        if terms:
            post.terms_names = terms

        API.call(NewPost(post))
Example #7
0
def create_new_empty_wp_post(component, event_category, event_map_location, location_gps):

    summary = component.get('SUMMARY').encode('UTF-8', 'backslashreplace')
    start_event = component.get('DTSTART').dt.strftime('%Y-%m-%d %H:%M')
    end_event = component.get('DTEND').dt.strftime('%Y-%m-%d %H:%M')
    end_frequency_event = component.get('DTEND').dt.strftime('%Y-%m-%d')
    uid = component.get('UID').encode('UTF-8', 'backslashreplace')
    event_description = component.get('DESCRIPTION')
    if event_description is None:
        event_description = " "
    else:
        event_description = component.get('DESCRIPTION').encode('UTF-8', 'backslashreplace')

    # Create a new post
    new_post = WordPressPost()
    new_post.title = summary
    new_post.content = event_description
    new_post.post_type = "event"
    new_post.post_status = "publish"
    new_post.terms_names = {'event-category': [event_category]}
    new_post.custom_fields = []

    meta_adds = (['imic_event_start_dt', start_event],
                 ['imic_event_end_dt', end_event],
                 ['imic_event_frequency_end', end_frequency_event],
                 ['imic_featured_event', 'no'],
                 ['slide_template', 'default'],
                 ['imic_event_day_month', 'first'],
                 ['imic_event_week_day', 'sunday'],
                 ['imic_event_frequency_type', '0'],
                 ['imic_event_frequency', '35'],
                 ['imic_event_registration', '0'],
                 ['imic_custom_event_registration_target', '0'],
                 ['imic_sidebar_columns_layout', '3'],
                 ['imic_google_map_track', '1'],
                 ['imic_event_address2', event_map_location],
                 ['imic_event_map_location', location_gps],
                 ['imic_pages_banner_overlay', '0'],
                 ['imic_pages_banner_animation', '0'],
                 ['imic_pages_select_revolution_from_list', '[rev_slider fsl]'],
                 ['imic_pages_slider_pagination', 'no'],
                 ['imic_pages_slider_auto_slide', 'no'],
                 ['imic_pages_slider_direction_arrows', 'no'],
                 ['imic_pages_slider_interval', '7000'],
                 ['imic_pages_slider_effects', 'fade'],
                 ['imic_pages_nivo_effects', 'sliceDown'],
                 ['imic_import_uid', uid])

    # Iterate over array creating meta in post
    for i in meta_adds:
        new_post.custom_fields.append({'key': i[0], 'value': i[1]})

    return new_post
Example #8
0
def postwpchallenge(title, content, tags, categories, wp, type="challenge"):
    #title (string), content (string/html), tags (list), categories (list), wp (Client Class), type (string)

    post = WordPressPost()
    post.post_type = type

    post.title = title
    post.content = content

    post.terms_names = {'post_tag': tags, 'category': categories}
    wp.call(NewPost(post))

    print("Challenge Posted to WordPress")
Example #9
0
def sourcename(url, cat1=None, cat2=None, cat3=None, d=True):
    html = getPage(url, "page1.html")
    os.remove('pages/page1.html')
    title = html.select('h1')[0].text
    first_para = html.select('.story-content > p:nth-of-type(1)')[0].text
    second_para = html.select('.story-content > p:nth-of-type(2)')[0].text
    try:
        image = html.select('.image > img')[0].get('src')
    except Exception:
        image = None
    wp = Client('http://www.domain.com/xml-rpc.php', 'username', 'password')
    if image:
        filename = 'http://www.livemint.com' + image
        path = os.getcwd() + "\\00000001.jpg"
        f = open(path, 'wb')
        f.write(urllib.urlopen(filename).read())
        f.close()
        # prepare metadata
        data = {
            'name': 'picture.jpeg',
            'type': 'image/jpeg',  # mimetype
        }

        with open(path, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
    post = WordPressPost()
    post.title = title
    post.user = 14
    post.post_type = "post"
    post.content = first_para + '\n' + '\n' + second_para
    if d:
        post.post_status = "draft"
    else:
        post.post_status = "publish"
    if image:
        attachment_id = response['id']
        post.thumbnail = attachment_id
    post.custom_fields = []
    post.custom_fields.append({'key': 'custom_source_url', 'value': url})
    if cat1:
        cat1 = wp.call(taxonomies.GetTerm('category', cat1))
        post.terms.append(cat1)
    if cat2:
        cat2 = wp.call(taxonomies.GetTerm('category', cat2))
        post.terms.append(cat2)
    if cat3:
        cat3 = wp.call(taxonomies.GetTerm('category', cat3))
        post.terms.append(cat3)
    addpost = wp.call(posts.NewPost(post))
Example #10
0
def post_article(title, body, category, tag):
    """发布一篇文章"""
    try:
        post = WordPressPost()
        post.title = title
        post.content = body
        post.post_status = "publish"  # draft草稿
        post.post_type = "post"  # page页面
        post.comment_status = 'open'  # 允许评论
        post.date_modified = datetime.datetime.now()
        post.terms_names = {'category': category, 'post_tag': tag}
        wp.call(NewPost(post))
        log("发布文章:%s..." % title[0:20])
    except Exception as e:
        log_error("文章发布失败!", e)
Example #11
0
def _create_wp_post(song, content):
    # Create the NewPost object - see docs at
    # http://python-wordpress-xmlrpc.readthedocs.io/en/latest/ref/wordpress.html
    # We're missing some fields but ehhhh who knows if they even exist anymore
    post = WordPressPost()
    post.title = str(song)
    post.content = content
    post.comment_status = 'open'
    post.ping_status = 'closed'
    post.post_status = 'publish'
    post.post_type = 'post'
    post.excerpt = song.tagline
    post.date = datetime.now(tz=timezone.utc)
    post.date_modified = datetime.now(tz=timezone.utc)

    return NewPost(post)
Example #12
0
def parseDocument(filename):
    lines = open(filename, 'r').readlines()
    values = {'title':'', 'permalink':'', 'layout':'post', 'tags':'', 'categories':'default', 'published': 'false'}
    start = False
    config = False
    for i in range(len(lines)):
        line = lines[i].strip()
        if config == False:
            if line == '---':
                if (start == False):
                    start = True
                else: # end
                    if (values['title'] == '' or values['permalink'] == ''):
                        printf('title and permalink should not be null!\n'); exit()
                    else:# config ok 
                        config = True
            else:
                try:
                    key = line[:line.find(':')]
                    value = line[line.find(':')+1:]
                    values[key] = value.strip()
                except:
                    printf('config failed! (key, value) = (' + key + ', ' + value + ')\n');exit()
        else: #config ok
            while len(lines[i]) <= 1: #filter first blank lines
                i+=1
            rawcontent = parseMedia(lines[i:])
            rawfilename = filename[:-3] + '.raw.id-'
            open(rawfilename, 'w').writelines(rawcontent)
            post = WordPressPost()
            post.title = values['title']
            post.slug = values['permalink']
            post.content = pandocTool.md2html(rawfilename)
            post.post_type = values['layout']
            post.post_status = 'publish' if values['published'].lower() == 'true' else 'draft'
            post.comment_status = 'open' #default
            post.pint_status = 'open' #default
            post.terms_names = {}
            #values['tags'] = values['tags'].replace(',', ',') compatible with jekyll, use blank
            #values['categories'] = values['categories'].replace(',', ',')
            if len(values['tags']) > 0:
                post.terms_names['post_tag'] = [ tag.strip() for tag in values['tags'].split() if len(tag) > 0] 
            if len(values['categories']) > 0:
                post.terms_names['category'] = [ cate.strip() for cate in values['categories'].split() if len(cate) > 0] 
            return post
Example #13
0
    def post_to_wordpress(
        self,
        title,
        content,
        detail_url,
        image_upload_id,
        retry,
        ):
        
        # now post the post and the image
        post = WordPressPost()
        post.post_type = 'portfolio'
        post.title = title
        post.content = content
        post.post_status = 'publish'
        post.thumbnail = image_upload_id

        if self.wp.call(NewPost(post)):
            return True
Example #14
0
def _add_blogpost(post_data):
    '''
    Adds a blog post parsed from blog.blogpost

    Model published status codes are as follows:  PUBLISHED = 1, DRAFT = 2, DELETED = 3

    :param post_data: Python dict of post structure.  See modelsamples/blogpost_sample.txt for structure.
    :return:
    '''
    post = WordPressPost()
    post.post_type = 'news'
    post.title = post_data['fields']['title']
    post.content = post_data['fields']['content']
    post.date = _return_datetime(post_data['fields']['publish_date'])
    post.date_modified = _return_datetime(post_data['fields']['updated'])
    post.slug = post_data['fields']['slug']
    if post_data['fields']['status'] == 2:
        post.post_status = 'publish'
    # Assign Author
    if post_data['fields']['user']:
        wp_userid = _get_wordpress_user_id_by_email(
            _get_django_user_email_by_id(post_data['fields']['user']))
        if wp_userid:
            post.user = wp_userid
    # TODO set catagories and tags to proper taxonomy
    # post.terms_names = {
    #     'category': ['Blogpost']
    # }
    # if post_data['fields']['categories']:
    #     categories = []
    #     for category in dp.get_content(DJANGO_DATA, 'blog.blogcategory'):
    #         if category['pk'] in post_data['fields']['categories']:
    #             categories.append(category['fields']['title'])
    #     post.terms_names['post_tag'] = categories
    try:
        if post_data['fields']['status'] != 3:
            post.id = API.call(NewPost(post))
            print("created post", post.id, post.title)
    except Fault as err:
        pprint(post)
        print(err.faultCode, err.faultString)
Example #15
0
def _add_application(app_data):
    '''
    Adds an application parse from apps.application

    :param app_data: Python dict of application structure. See modelsamples/application_sample.txt
    :return:
    '''
    post = WordPressPost()
    post.post_type = 'application'
    post.title = app_data['fields']['name']
    post.slug = app_data['fields']['slug']
    post.content = _format_app_content(app_data)
    post.date = _return_datetime(app_data['fields']['created'])
    post.date_modified = _return_datetime(app_data['fields']['updated'])

    # TODO assign to proper taxonomies once those are in.

    # Assign Author
    if app_data['fields']['owner']:
        wp_userid = _get_wordpress_user_id_by_email(
            _get_django_user_email_by_id(app_data['fields']['owner']))
        if wp_userid:
            post.user = wp_userid

    # Assign Categories and Tags
    post.terms_names = _parse_taxonomies(app_data)

    # Put the previous page url in a custom field.
    legacy_url = "https://www.us-ignite.org/apps/%s/" % (
        app_data['fields']['slug'])
    post.custom_fields = [{'key': 'legacy_url', 'value': legacy_url}]

    # Set publish status and push to site
    if app_data['fields']['status'] == 1:
        post.post_status = 'publish'
    try:
        if app_data['fields']['status'] != 3:
            post.id = API.call(NewPost(post))
    except Fault as err:
        pprint(err.faultString)
Example #16
0
def uploadPost(postType, artist, album, song, artwork, connection):
    albumType, releaseDate = getInfo(artist, album)
    post = WordPressPost()
    post.post_type = 'download'
    if postType == 'bundle':
        post.title = album
    else:
        post.title = song
        post.content, keyword = getContent(artist, album, song)
    post.date = datetime.datetime.strptime(releaseDate, '%Y.%m.%d')
    post.terms = wp.call(
        taxonomies.GetTerms('download_artist', {'search': artist}))
    post.thumbnail = artwork
    post.custom_fields = []
    post.post_status = 'publish'
    post.custom_fields.append({'key': 'year', 'value': releaseDate})
    post.custom_fields.append({'key': 'music_type', 'value': postType})
    post.id = wp.call(posts.NewPost(post))
    with connection.cursor() as cursor:
        if postType == 'bundle':
            sql = 'INSERT INTO `upload_info` (`item_type`, `album_type`, `artist`, `album`, `post_title`, `release_date`, `thumbnail_id`, `post_id`, `published`, `updated_at`) VALUES (%s, %s, %s,%s,%s,%s,%s,%s,%s, now())'
            cursor.execute(sql,
                           (postType, albumType, artist, album, post.title,
                            post.date, post.thumbnail, post.id, '1'))
        else:
            sql1 = 'INSERT INTO `upload_info` (`item_type`, `album_type`, `artist`, `album`, `song`, `post_title`, `release_date`, `thumbnail_id`, `post_id`, `published`, `updated_at`) VALUES (%s, %s, %s,%s,%s,%s,%s,%s,%s,%s, now())'
            sql2 = 'INSERT INTO `wp9r_postmeta` (`post_id`, `meta_key`, `meta_value`) VALUES (%s, "_yoast_wpseo_focuskw_text_input", %s)'
            sql3 = 'INSERT INTO `wp9r_postmeta` (`post_id`, `meta_key`, `meta_value`) VALUES (%s, "_yoast_wpseo_focuskw", %s)'
            cursor.execute(
                sql1, (postType, albumType, artist, album, song, post.title,
                       post.date, post.thumbnail, post.id, '1'))
            cursor.execute(sql2, (post.id, keyword))
            cursor.execute(sql3, (post.id, keyword))
    if postType == 'bundle':
        print('Upload Successful for album %s - %s. Post id = %s' %
              (artist, album, post.id))
    else:
        print('Upload Successful for song %s - %s. Post id = %s' %
              (artist, song, post.id))
    return post.id
Example #17
0
def add_or_edit_wp_post(title, content, slug, more_info_url, local_img_file):

    # first upload the image
    if local_img_file:
        data = {
            'name': local_img_file.split('/')[-1],
            'type': 'image/jpg',  # mimetype
        }

        # read the binary file and let the XMLRPC library encode it into base64
        with open(local_img_file, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
        attachment_id = response['id']

    # now post the post and the image
    post = WordPressPost()
    post.post_type = 'post'  # stupid effing theme
    post.title = title
    post.content = content
    post.post_status = 'publish'
    post.slug = slug

    if local_img_file:
        post.thumbnail = attachment_id

    if not get_wp_post_id(slug):
        # this is a new post
        wp.call(NewPost(post))
        msg = "posted"

    else:
        # this post exists, update it
        post.id = get_wp_post_id(slug)
        wp.call(EditPost(post.id, post))
        msg = "edited"

    print "%s %s as %s" % (msg, title, post.slug)
Example #18
0
def post_to_wordpress(title, content, more_info_url, local_img_file):

    # first upload the image
    data = {
        'name': local_img_file.split('/')[-1],
        'type': 'image/jpg',  # mimetype
    }

    # read the binary file and let the XMLRPC library encode it into base64
    with open(local_img_file, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
    response = WP.call(media.UploadFile(data))
    attachment_id = response['id']

    # now post the post and the image
    post = WordPressPost()
    post.post_type = 'portfolio'  # hack for the salmoncream theme
    post.title = title
    post.content = content
    post.post_status = 'publish'
    post.thumbnail = attachment_id

    WP.call(NewPost(post))
Example #19
0
def upload_post(auth, **args):
    wp = Client(auth['site'], auth['user'], auth['pass'])

    post = WordPressPost()

    post.post_type = args.get('type', None)
    post.title = args.get('title', None)
    post.content = args.get('content', None)
    post.date = gen_datetime(args['date'], args.get('date-format', None),
                             args.get('zone', 0))

    terms = {key: [value] for key, value in args.get('terms', {}).items()}
    post.terms_names = terms

    if args.get('path', None) is not None:
        post.custom_fields = [{'key': 'enclosure',
                               'value': upload_media(args['path'], wp)
                               }]

    if args.get('publish', False):
        post.post_status = 'publish'

    post.id = wp.call(posts.NewPost(post))
Example #20
0
def createQuote(url):
    tags = "random"
    name = str(random.randint(100, 10000)) + '.png'
    attachment_id = ''
    idata = {
        'name': name,
        'type': 'image/png',  # mimetype
    }
    if (url['categories']):
        categories = ','.join(url['categories'])
    res = urllib.request.urlretrieve(
        'https://source.unsplash.com/800x400/?' + categories,
        "./img-quote/" + name)
    if (res):
        with open('./img-quote/' + name, 'rb') as img:
            idata['bits'] = xmlrpc_client.Binary(img.read())
        response = client.call(media.UploadFile(idata))
        attachment_id = response['attachment_id']

    print(bcolors.OKBLUE + " creating post " + bcolors.ENDC)
    postDate = datetime.now()
    post = WordPressPost()
    post.title = url['id']
    post.post_type = 'quotes'
    post.content = url['quote']
    post.post_status = "publish"
    post.author = "admin"
    post.date = postDate
    post.thumbnail = attachment_id
    post.terms_names = {
        'quotes_category': url['categories'],
    }
    post.custom_fields = []
    post.custom_fields.append({'key': 'q_author', 'value': url['author-id']})
    addpost = client.call(posts.NewPost(post))
    if (addpost):
        print(bcolors.OKGREEN + "post created " + bcolors.ENDC)
Example #21
0
    def _post_newpost_to_wordpress(self, item, attachment_id):
        post = WordPressPost()
        post.title = item['title']
        post.content = item['content']
        post.post_type = "post"
        post.post_status = "publish"
        post.terms_names = {
            'post_tag': item['tags'],
            'category': [item['url_from']]
        }
        post.custom_fields = []
        post.custom_fields.append({
            'key': 'custom_source_url',
            'value': item['url']
        })
        # cat1 = self.wp.call(taxonomies.GetTerm('category', 'wanghao'))
        # post.terms.append(cat1)

        if attachment_id:
            post.thumbnail = attachment_id

        addpost = self.wp.call(posts.NewPost(post))

        return addpost
    c = ''
    if os.path.isfile('pages/' + filename):
        print("Loading the data via the file.")
        f = open('pages/' + filename, 'r')
        c = f.read()
    else:
        print("Fetching the data via the URL.")
        result = requests.get(url)
        c = result.content
        f = open('pages/' + filename, 'w')
        f.write(c)
    f.close()
    c = BeautifulSoup(c)
    return c


html = getPage("http://news.ycombinator.com/", "page1.html")

rows = html.select('#hnmain > tr:nth-of-type(3) > td > table > tr')

for row in rows:
    if row.select('.title'):
        link = row.select('td:nth-of-type(3) a')
        print link[0].text
        post = WordPressPost()
        post.title = link[0].text
        post.post_type = "post"
        post.content = link[0].get('href')
        post.post_status = "publish"
        addpost = client.call(posts.NewPost(post))
Example #23
0
def parseDocument(filename):
    lines = open(filename, 'r').readlines()
    values = {
        'title': '',
        'permalink': '',
        'layout': 'post',
        'tags': '',
        'categories': 'default',
        'published': 'false'
    }
    start = False
    config = False
    for i in range(len(lines)):
        line = lines[i].strip()
        if config == False:
            if line == '---':
                if (start == False):
                    start = True
                else:  # end
                    if (values['title'] == '' or values['permalink'] == ''):
                        printf('title and permalink should not be null!\n')
                        exit()
                    else:  # config ok
                        config = True
            else:
                try:
                    key = line[:line.find(':')]
                    value = line[line.find(':') + 1:]
                    values[key] = value.strip()
                except:
                    printf('config failed! (key, value) = (' + key + ', ' +
                           value + ')\n')
                    exit()
        else:  #config ok
            while len(lines[i]) <= 1:  #filter first blank lines
                i += 1
            rawcontent = parseMedia(lines[i:])
            rawfilename = filename[:-3] + '.raw.id-'
            open(rawfilename, 'w').writelines(rawcontent)
            post = WordPressPost()
            post.title = values['title']
            post.slug = values['permalink']
            post.content = pandocTool.md2html(rawfilename)
            post.post_type = values['layout']
            post.post_status = 'publish' if values['published'].lower(
            ) == 'true' else 'draft'
            post.comment_status = 'open'  #default
            post.pint_status = 'open'  #default
            post.terms_names = {}
            #values['tags'] = values['tags'].replace(',', ',') compatible with jekyll, use blank
            #values['categories'] = values['categories'].replace(',', ',')
            if len(values['tags']) > 0:
                post.terms_names['post_tag'] = [
                    tag.strip() for tag in values['tags'].split()
                    if len(tag) > 0
                ]
            if len(values['categories']) > 0:
                post.terms_names['category'] = [
                    cate.strip() for cate in values['categories'].split()
                    if len(cate) > 0
                ]
            return post
def add_movies(page_num, choice):

    while True:

        if (choice == 'a' or choice == 'upcoming'):
            term_tag = 'upcoming'
            term_cat = 'upcoming'
            get_url = "/3/movie/upcoming?page=" + str(
                page_num
            ) + "&language=en-US&api_key=eedcd0a42e1921c7f3da84ad5fdeaa2a"

        if (choice == 'b' or choice == 'nowplaying'):
            term_tag = 'Now playing'
            term_cat = 'now_playing'
            get_url = "/3/movie/now_playing?page=" + str(
                page_num
            ) + "&language=en-US&api_key=eedcd0a42e1921c7f3da84ad5fdeaa2a"

        if (choice == 'c' or choice == 'archives' or choice == 'archive'):

            term_tag = 'archives'
            term_cat = 'archives'
            get_url = "/3/discover/movie?page=" + str(
                page_num) + "&language=en-US&primary_release_date.lte=" + str(
                    date) + "&api_key=eedcd0a42e1921c7f3da84ad5fdeaa2a"
        try:
            #making the connection to the api
            print("making the connection")
            conn = http.client.HTTPSConnection("api.themoviedb.org")
            payload = "{}"
            print("getting all the movies from page " + str(page_num))

            #getting the movies data , key = now playing
            print("making the api req")
            #print(get_url , term_cat , term_tag)

            conn.request("GET", get_url, payload)
            res = conn.getresponse()
            data = res.read()
            response = json.loads(data.decode("utf-8"))

            #connecting to wordpress
            wp = Client('http://172.104.189.102/xmlrpc.php', 'octraves',
                        'octraves')

            # THE MAIN LOOP FOR ADDING ALL THE MOVIES TO THE WP DATABASE
            counter = 1
            for movie in response['results']:
                try:

                    print("Adding movie number = " + str(counter) + "id :  " +
                          str(movie['id']))
                    #download and upload the image to wordpress
                    url = "http://image.tmdb.org/t/p/w200" + movie[
                        'poster_path']
                    image_name = str(movie['id']) + '.jpg'
                    image_location = '/Users/user/Desktop/wordpress_images/' + image_name
                    urllib.request.urlretrieve(
                        url, image_location)  # download the image
                    image = image_location
                    imageType = mimetypes.guess_type(str(image))[0]
                    img_data = {
                        'name': image_name,
                        'type': imageType,
                    }
                    with open(image, 'rb') as img:
                        img_data['bits'] = xmlrpc_client.Binary(img.read())

                    img_response = wp.call(media.UploadFile(img_data))
                    attachment_id = img_response[
                        'id']  # id to be appended in post

                    #getting the trailer
                    try:
                        link = details.get_trailer(movie['id'])
                    except:
                        link = ""
                        pass

                    # Creating custom fields
                    fields = [['Languages', movie['original_language']],
                              ['Release Date', movie['release_date']]]

                    # Creating the post
                    post = WordPressPost()
                    post.title = movie['title']
                    post.post_type = 'post'
                    post.mime_type = "text/html"
                    post.content = genres.get_primary_info(
                        movie['id']
                    ) + """<h3> Overview </h3> """ + movie[
                        'overview'] + """<h3> Trailer </h3> """ + " \n" + link + " \n" + " \n" + " \n" + """<h3> Credits </h3> """ + " \n" + " \n" + " \n" + str(
                            details.get_credits(movie['id'],
                                                'cast')) + details.get_poster(
                                                    movie['id'])

                    post.thumbnail = attachment_id
                    post.terms_names = {
                        'post_tag': [term_tag],
                        term_cat: genres.get_genres(movie['genre_ids']),
                        'category': genres.get_genres(movie['genre_ids'])
                    }

                    post.custom_fields = []
                    for field in fields:
                        post.custom_fields.append({
                            'key': field[0],
                            'value': field[1]
                        })
                    post.post_status = 'publish'
                    post.comment_status = 'open'

                    #finally publish the post !!
                    post.id = wp.call(posts.NewPost(post))

                    #add comments
                    reviews = details.get_reviews(movie['id'])
                    for review in reviews:
                        comment = WordPressComment()
                        comment.author = review['author']
                        comment.content = review['content']
                        wp.call(comments.NewComment(post.id, comment))

                    counter += 1

                except Exception as e:
                    print(
                        "All the pages have been processed or there is a error!!  "
                        + str(e))
                    pass

            print("Page number " + str(page_num) +
                  " is completed ! Loading another page.")

            page_num += 1

        except Exception as e:
            print(str(e))
&nbsp;

பிற வடிவங்களில் படிக்க  – ''' + book_url + '''


புத்தக எண் - ''' + str(book_number) + '''


'''

print("Publising the Ebook")
content = content + extra

post.title = book_title + " - " + category + " - " + author
post.slug = book_title_in_english
post.post_type = 'ebooks'

post.content = content

post.thumbnail = attachment_id
post.comment_status = 'open'

post.post_status = 'publish'
#post.post_status = 'draft'

if artist:
    post.terms_names = {
        'genres': [category],
        'contributors': [artist, ebook_maker],
        'authors': [author]
    }
Example #26
0
def createWPEvent(eventType, event):
    configuration = json.loads(open('config.json').read())
    wp = Client('https://greateraustinsecularhub.org/xmlrpc2.php', configuration['wpUser'], configuration['wpKey'])
    post = WordPressPost()
    post.post_type = 'events'
    if eventType == 'meetup':
        post.title = event['name']
        post.content = ""

        #If the event is public, note the details.
        eventLocation = "See event details"
        if event['visibility'] == 'public':
            eventLocation = event['venue']['name']
        
        eventTags = getTags(event['name'], event['description'])
        post.terms_names = {
            'post_tag': eventTags,
            #'venue': [eventLocation],
            'organizer': [event['group']['name']]
        }
        
        eventStartDateTime_Datetime = datetime.fromtimestamp((event['time']+event['utc_offset'])/1000)  
        eventEndDateTime_Datetime = datetime.fromtimestamp((event['time']+event['utc_offset']+event['duration'])/1000) 

        eventStartTime = eventStartDateTime_Datetime.strftime("%H:%M")
        eventEndTime = eventEndDateTime_Datetime.strftime("%H:%M")
        eventStartTime_Pretty = eventStartDateTime_Datetime.strftime("%-I:%M %P")
        eventEndTime_Pretty = eventEndDateTime_Datetime.strftime("%-I:%M %P")
        eventStartDateTime = eventStartDateTime_Datetime.strftime("%Y-%m-%d")
        eventEndDateTime = eventEndDateTime_Datetime.strftime("%Y-%m-%d")
        post.excerpt = configuration['wpInfoBox'] % (event['group']['name'], eventStartTime_Pretty, eventEndTime_Pretty, eventLocation, ', '.join(eventTags), event['event_url'], event['event_url'], event['description'][:200])
        post.custom_fields = [{'key': 'fc_allday','value': 0},
                            {'key': 'fc_start','value':eventStartDateTime},
                            {'key': 'fc_start_time','value': eventStartTime},
                            {'key':'fc_end','value':eventEndDateTime},
                            {'key':'fc_end_time','value': eventEndTime},
                            {'key':'fc_interval', 'value':''},
                            {'key':'fc_end_interval', 'value':''},
                            {'key': 'fc_dow_except', 'value':''},
                            {'key':'fc_color', 'value':'#'},
                            {'key':'fc_text_color', 'value':'#'},
                            {'key':'fc_click_link', 'value':'view'},
                            {'key':'fc_click_target', 'value':'_blank'},
                            {'key':'fc_exdate', 'value':''},
                            {'key':'fc_rdate', 'value':''},
                            {'key':'fc_event_map', 'value':''},
                            {'key':'enable_featuredimage', 'value':1},
                            {'key':'enable_postinfo', 'value':1},
                            {'key':'enable_postinfo_image', 'value':1},
                            {'key':'enable_venuebox', 'value':1},
                            {'key':'enable_venuebox_gmap', 'value':1},
                            {'key':'rhc_top_image', 'value':''},
                            {'key':'rhc_dbox_image', 'value':''},
                            {'key':'rhc_tooltip_image', 'value':''},
                            {'key':'rhc_month_image', 'value':''},
                            {'key': 'meetupID', 'value': event['id']},
                            {'key': 'meetupLastUpdated', 'value': int(event['updated']/1000)}]
    #pdb.set_trace()
    post.post_status = 'publish'
    #pprint(post)
    post.id = wp.call(NewPost(post))
    time.sleep(0.5)
    return
            if val['lastDate']:
                lastDate = datetime.strptime(val['lastDate'],
                                             '%b %d, %Y').strftime('%Y-%m-%d')
            else:
                lastDate = ''

            adType = val['adType']
            company = val['company']
            logo = val['logo']
            vacancies = val['vacancies']
            external = val['external']

            new_job = WordPressPost()
            new_job.title = title
            new_job.content = description
            new_job.post_type = 'job_listing'
            new_job.post_status = 'publish'

            new_job.id = wp.call(posts.NewPost(new_job))

            taxes = wp.call(taxonomies.GetTerms('job_listing_type'))
            is_present = 0
            post_category_id = 0

            for val in taxes:
                if str(val) == str(type):
                    is_present = 1
                    post_category_id = val.id
                    break

            if is_present == 0:
Example #28
0
			businessEntity = val['businessEntity']
			industry = val['industry']
			description = val['description']
			website = val['website']
			city = val['city']
			country = val['country']
			rating = val['rating']
			reviewsCount = val['reviewsCount']
			jobsCount = val['jobsCount']
			latestReview = val['latestReview']
			logo = val['logo']
			
			new_company = WordPressPost()
			new_company.title = name
			new_company.content = description
			new_company.post_type = 'company'
			new_company.post_status = 'publish'
			
			new_company.id = wp.call(posts.NewPost(new_company))

			taxes = wp.call(taxonomies.GetTerms('company_category'))
			is_present = 0
			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:
Example #29
0
def main():
    args = sys.argv[1:]
    if len(args) != 2:
        print(
            'Usage: ./ssp_se_load_roster.py <Wordpress xmlrpc url> <csvfile>')
        sys.exit(1)

    xmlrpc = args[0]
    csvfile_name = args[1]

    if not os.path.isfile(csvfile_name):
        print('I can\'t find the file: ' + csvfile_name)
        sys.exit(1)

    username = raw_input('Enter your WordPress user name: ')
    password = getpass()

    wp = Client(xmlrpc, username, password)

    listofseriesterms = wp.call(GetTerms('series'))

    print('To which series are you going to add all these posts? (id, name)')
    series = {}
    for seriesterm in listofseriesterms:
        print(seriesterm.id + ', ' + seriesterm.name)
        series[seriesterm.id] = seriesterm.name
    main_series_termid = raw_input('Please enter the id: ')

    if not main_series_termid in series:
        print('That series id does not exist')
        sys.exit(1)
    else:
        print(series[main_series_termid] + ' series selected.')

    child_series = {}
    for seriesterm in listofseriesterms:
        if seriesterm.parent == main_series_termid:
            child_series[seriesterm.name.lower()] = seriesterm.id

    print('child_series')
    print(child_series)

    existing_posts = wp.call(GetPosts({
        'post_type': 'podcast',
        'number': 9999
    }))
    existing_series_posts = {}
    child_series_existing_episode_numbers = {}
    for post in existing_posts:
        post_terms = []
        for term in post.terms:
            if term.id in child_series.values(
            ) or term.id == main_series_termid:
                post_terms.append(term.id)
        if post_terms:
            for customfield in post.custom_fields:
                if customfield['key'] == 'date_recorded' and customfield[
                        'value']:
                    date_recorded_string = customfield['value']
                elif customfield['key'] == 'episode_number' and customfield[
                        'value']:
                    for post_term_id in post_terms:
                        if post_term_id in child_series_existing_episode_numbers:
                            child_series_existing_episode_numbers[
                                post_term_id].append(int(customfield['value']))
                        else:
                            child_series_existing_episode_numbers[
                                post_term_id] = [int(customfield['value'])]
            date_recorded = getdatetime(date_recorded_string)
            existing_series_posts[date_recorded] = (post.id, post_terms)

    #open and parse the csv
    replace_all = False
    replace_none = False

    fieldname_translation = {
        'date': 'date_recorded',
        'title': 'title',
        'series': 'series',
        'track': 'episode_number',
        'passage': 'bible_passage',
        'preacher': 'preacher',
        'comments': 'content',
        'time': 'time'
    }

    list_from_csv = {}
    with open(csvfile_name, 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        for messyentry in reader:
            entry = {}
            for entrykey, entryval in messyentry.iteritems():
                entry[fieldname_translation[entrykey.lower()]] = entryval
            if not (('date_recorded' in entry) or ('preacher' in entry)):
                continue
            if entry['date_recorded'] == '' or entry['preacher'] == '':
                continue
            csvdate = getdatetime(entry['date_recorded'])
            if csvdate == None:
                continue
            entry['date_recorded'] = csvdate.strftime('%d-%m-%Y')
            try:
                int(entry['episode_number'])
            except (ValueError, KeyError):
                entry['episode_number'] = ''
            for fieldname in fieldname_translation.values():
                if not fieldname in entry:
                    entry[fieldname] = ''
            if not entry['series']:
                entry['series'] = 'one-off'
            if (csvdate in existing_series_posts):
                if not (replace_none or replace_all):
                    confirmation_raw_in = raw_input(
                        'There is already a podcast in this series with date '
                        + csvdate.strftime('%d %b %Y') +
                        ', replace it? \n(Y/N/All/None)\n').lower()
                elif replace_none:
                    continue
                if confirmation_raw_in == 'none':
                    replace_none = True
                if not confirmation_raw_in in ['y', 'all']:
                    continue
                if confirmation_raw_in == 'all':
                    replace_all = True
                if wp.call(DeletePost(existing_series_posts[csvdate][0])):
                    print('Deleted old post for ' +
                          csvdate.strftime('%d %b %Y') + '.')
            entry['bible_passage'] = cleanUpScripture(entry['bible_passage'])
            list_from_csv[csvdate] = entry

    template_settings = {
        'ep_title_template': 'title',
        'service_time': 'time',
        'comments_template': 'content'
    }

    #work out series and episode_numbers:
    for seriestermid in child_series_existing_episode_numbers:
        try:
            child_series_existing_episode_numbers[seriestermid] = sorted(
                child_series_existing_episode_numbers[seriestermid],
                reverse=True)[0]
        except IndexError as e:
            print(e)
            try:
                child_series_existing_episode_numbers[seriestermid] = int(
                    series[seriestermid].count)
            except:
                child_series_existing_episode_numbers[seriestermid] = 0

    prefix = 'ss_podcasting_data_'
    termidlist = ['0', main_series_termid]
    optionslist = []
    templates_per_series = {}
    for child_series_termid in child_series.values():
        termidlist.append(child_series_termid)
    for termid_item in termidlist:
        templates_per_series[termid_item] = {}
        if termid_item == '0':
            suffix = ''
        else:
            suffix = '_' + termid_item
        for eachsetting in template_settings:
            optionslist.append(prefix + eachsetting + suffix)
    list_of_WPOptions = wp.call(GetOptions(optionslist))
    for wp_Option in list_of_WPOptions:
        if wp_Option.name[len(prefix):] in template_settings:
            templates_per_series['0'][
                wp_Option.name[len(prefix):]] = wp_Option.value
        else:
            for termid_item in termidlist:
                suffix = '_' + termid_item
                if wp_Option.name[-len(suffix):] == suffix:
                    templates_per_series[termid_item][wp_Option.name[
                        len(prefix):-len(suffix)]] = wp_Option.value

    timezone = get_localzone()

    for entry, details in sorted(list_from_csv.iteritems()):
        if not details['series'].lower() in child_series:
            wpseries = WordPressTerm()
            wpseries.taxonomy = 'series'
            wpseries.name = details['series']
            wpseries.parent = main_series_termid
            wpseries.id = wp.call(NewTerm(wpseries))
            child_series[details['series']] = wpseries.id
            listofseriesterms.append(wpseries)
            series[wpseries.id] = wpseries.name
            child_series[wpseries.name.lower()] = wpseries.id
            if details['episode_number'] == '':
                details['episode_number'] = '1'
                child_series_existing_episode_numbers[wpseries.id] = 1
            else:
                child_series_existing_episode_numbers[wpseries.id] = int(
                    details['episode_number'])
            details['seriesid'] = wpseries.id
        else:
            try:
                child_series_existing_episode_numbers[child_series[
                    details['series'].lower()]]
            except KeyError:
                for seriesterm in listofseriesterms:
                    if seriesterm.id == child_series[
                            details['series'].lower()]:
                        child_series_existing_episode_numbers[child_series[
                            details['series'].lower()]] = seriesterm.count
                    else:
                        child_series_existing_episode_numbers[child_series[
                            details['series'].lower()]] = 0
            if details['episode_number'] == '':
                child_series_existing_episode_numbers[child_series[
                    details['series'].lower()]] += 1
                details['episode_number'] = str(
                    child_series_existing_episode_numbers[child_series[
                        details['series'].lower()]])
            else:
                child_series_existing_episode_numbers[child_series[
                    details['series'].lower()]] = int(
                        details['episode_number'])
            details['seriesid'] = child_series[details['series'].lower()]
        for template_setting, detail in template_settings.iteritems():
            list = [details['seriesid'], main_series_termid, '0']
            while details[detail] == '':
                try:
                    details[detail] = templates_per_series[list.pop(
                        0)][template_setting]
                except KeyError:
                    continue
        publishtime = gettime(details['time'])
        if publishtime:
            local_datetime = timezone.localize(
                datetime.combine(entry, publishtime.time()))
            details['post_date_gmt'] = local_datetime.astimezone(pytz.utc)
        newpost = WordPressPost()
        newpost.post_type = 'podcast'
        newpost.title = details['title']
        newpost.date = details['post_date_gmt']
        newpost.post_status = 'draft'
        newpost.content = details['content']
        newpost.terms = [wp.call(GetTerm('series', main_series_termid))]
        if details['seriesid']:
            newpost.terms.append(
                wp.call(GetTerm('series', details['seriesid'])))
        newpost.custom_fields = [{
            'key': 'preacher',
            'value': details['preacher']
        }, {
            'key': 'date_recorded',
            'value': details['date_recorded']
        }, {
            'key': 'bible_passage',
            'value': details['bible_passage']
        }, {
            'key': 'episode_number',
            'value': details['episode_number']
        }, {
            'key': 'publish_now',
            'value': 'on'
        }]
        newpost.id = wp.call(NewPost(newpost))
        if newpost.id:
            print('Created Post ID ' + str(newpost.id) + ' for date: ' +
                  details['date_recorded'])
Example #30
0
    def createPost(self, attachmentID):
        """ 
       
        Creates Posts in CMS. 
        ----------        

        After successfull Authentication, this function sets a post title, post status and 
        generates the post with the postmeta fields for the image, date and time. 
        ----------              
        
        Parameters: 
        ----------        
        attachmentID (int): ID of the Image, that should be attached to the post.
        
        Returns: 
        ----------        
        nothing will be returned. 
      
        """

        # Generate Post Object
        post = WordPressPost()
        post.post_type = self.post_configuration.postBasicInformation.get(
            'post_type')
        post.title = time.strftime("%A, %d, %B um %H:%M:%S", self.time)

        # Authentification
        authenticator = Authenticator.Authenticator()
        credentials = authenticator.obtainCredentials(User.User())
        cms = authenticator.isValid(credentials)
        post = WordPressPost()

        if 'post_type' in self.post_configuration.postBasicInformation:
            post.post_type = self.post_configuration.postBasicInformation.get(
                'post_type')

        post.title = time.strftime("%A, %d, %B um %H:%M:%S", self.time)

        # Prepare Key-Value-Pairs for upload to CMS
        custom_post_configuration = self.post_configuration.postCustomFields

        if 'imageField' in custom_post_configuration:
            self.image = {
                'key': custom_post_configuration.get('imageField'),
                'value': self.attachmentID
            }

        if 'dateField' in custom_post_configuration:
            self.date = {
                'key': custom_post_configuration.get('dateField'),
                'value':
                time.strftime("%Y%m%d",
                              self.time)  # zum Beispiel 20190116, also %Y%m%e
            }

        if 'timeField' in custom_post_configuration:
            self.time = {
                'key': custom_post_configuration.get('timeField'),
                'value': time.strftime(
                    "%T", self.time
                )  # zum Beispiel 02:12:17, also %T --> entspricht %H:%M:%S        
            }

        if 'timestampField' in custom_post_configuration:
            self.timestamp = {
                'key': custom_post_configuration.get('timestampField'),
                'value': self.setting.filename
            }

        # create list with the key-value-pairs
        post.custom_fields = [self.image, self.date, self.time, self.timestamp]

        # publish the Posts according to the default setting or set different post status according to PostBasicInformation.
        if 'post_status' in self.post_configuration.postBasicInformation:
            post.post_status = self.post_configuration.postBasicInformation.get(
                'post_status')

        # Generate the post
        cms.call(NewPost(post))


#==========================================================================
# END
#==========================================================================
        # 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']
        #print 'Attachment ID:', attachment_id

        #find date and time for title of picture
        i = datetime.now()
        gym = 'BKB '
        print i.strftime('%b %d %X')

        #Create post
        post = WordPressPost()
        post.post_type = 'sell_media_item'
        post.title = gym + i.strftime('%b %d %X')
        post.post_status = 'publish'
        post.thumbnail = attachment_id
        post_id = post.id = client.call(posts.NewPost(post))

        #move file from Pictures folder to UploadedPictures folder
        os.chdir('..')
        os.rename(os.path.join(path, oldest),
                  os.path.join('OldPictures', oldest))
        #update num_files
        num_files = len([
            f for f in os.listdir(path)
            if os.path.isfile(os.path.join(path, f))
        ])
        #print num_files
        exit()
    c = ''
    if os.path.isfile('pages/'+filename):
        print("Loading the data via the file.")
        f = open('pages/'+filename, 'r')
        c = f.read()
    else:
        print("Fetching the data via the URL.")
        result = requests.get(url)
        c = result.content
        f = open('pages/'+filename,'w')
        f.write(c)
    f.close()
    c = BeautifulSoup(c)
    return c

html = getPage("http://news.ycombinator.com/", "page1.html")

rows = html.select('#hnmain > tr:nth-of-type(3) > td > table > tr');

for row in rows:
    if row.select('.title'):
        link = row.select('td:nth-of-type(3) a')
        print link[0].text
        post = WordPressPost()
        post.title = link[0].text
        post.post_type = "post"
        post.content = link[0].get('href')
        post.post_status = "publish"
        addpost = client.call(posts.NewPost(post))
os.system(ia_upload)

audioURL = "https://archive.org/download/%s/%s" % (
    ia_identifier, audioTitleInEnglish + ".mp3")
print("Uploaded to " + audioURL)

print("Posting into WordPress")

wp_username = audio_info['wp_username']
wp_password = audio_info['wp_password']

wpBlogUrl = audio_info['wp_blog_url'] + '/xmlrpc.php'
client = Client(wpBlogUrl, wp_username, wp_password)
post = WordPressPost()

content = "%s \n %s" % (audioURL, audioComments)
post.title = title
post.content = content
post.post_status = 'publish'
post.comment_status = 'open'
post.terms_names = {'category': ['Podcast']}
post.slug = audioTitleInEnglish

if "kaniyam.com" in wpBlogUrl:
    post.post_type = 'podcast'
    post.terms_names = ""
    print("Publishing to Kaniyam")

post.id = client.call(posts.NewPost(post))

print("Posted into WordPress")
def toWP(single_event):

    #tituloFoto = uuid.uuid4()
    tituloFoto = randomword(9)

    data = {
        'name': tituloFoto + '.jpg',
        'type': 'image/jpeg',  # mimetype
    }

    file = get_url_content(single_event['foto'])

    data['bits'] = xmlrpc_client.Binary(file)

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

    attachment_id = response['id']
    widget = WordPressPost()
    widget.post_type = 'event_type'
    widget.title = single_event['title']
    widget.content = single_event['descripcion']
    widget.thumbnail = attachment_id
    widget.custom_fields = []
    widget.custom_fields.append({
        'key': 'coord',
        'value': {
            "address": single_event['direccion'],
            "lat": single_event['latitude'],
            "lng": single_event['longitude']
        }
    })
    widget.custom_fields.append({
        'key': 'fecha_inicio',
        'value': single_event['fecha_inicio']
    })
    widget.custom_fields.append({
        'key': 'direccion',
        'value': single_event['direccion']
    })
    widget.custom_fields.append({
        'key': 'fecha_fin',
        'value': single_event['fecha_fin']
    })
    widget.custom_fields.append({'key': 'telefono', 'value': ""})
    widget.custom_fields.append({'key': 'correo_electronico', 'value': ""})
    widget.custom_fields.append({
        'key': 'pagina_web',
        'value': "www.peque-agenda.com"
    })
    widget.custom_fields.append({
        'key':
        'edad',
        'value':
        single_event['edadMin'] + ';' + single_event['edadMax']
    })
    widget.custom_fields.append({
        'key': 'precio',
        'value': single_event['precio']
    })
    widget.custom_fields.append({
        'key': 'imagen_evento',
        'value': randint(400, 718)
    })

    widget.id = client.call(posts.NewPost(widget))
Example #35
0
            tags = []
            if (a['featured']):
                tags.append('Featured')
            if (a['image']):
                num = str(random.randint(100, 25000))
                name = num + a['author'] + '.png'
                data = {
                    'name': name,
                    'type': 'image/png',  # mimetype
                }
                res = urllib.request.urlretrieve(a['image'],
                                                 "./images/" + name)
                if (res):
                    with open('./images/' + name, 'rb') as img:
                        data['bits'] = xmlrpc_client.Binary(img.read())
                    response = client.call(media.UploadFile(data))
                    attachment_id = response['attachment_id']
            if a['author'] and len(a['author']) >= 1:
                # try:

                post = WordPressPost()
                post.title = a['author']
                post.post_type = 'q_author'
                post.post_status = "publish"
                post.terms_names = {'post_tag': tags}
                post.thumbnail = attachment_id
                addpost = client.call(posts.NewPost(post))
            # except:
            #     exit()
            #     pass