0

I have a below function in my python script from where I want to exectute two other functions and these depends on the value of PageId and ver if it is null then it should execute write_data_null(auth, html, title) else it should execute write_data_not_null(auth, html, pageId, title) function.The first function overwrites the data on wiki on the existing page and second function creates the page and write the data on wiki.

To know whether the page exist already I wrote one function which gives me the value of PageId and if it doesn't exist it gives me error message "IndexError: list index out of range" .I am fine with that.My intention is if it gives me this error then I would assume that page doesn't exist and it should execute write_data_null function successfully.

Could someone tell me how could I achieve this?

import argparse
import sys

import requests
import json

BASE_URL = "https://wiki.host.com/rest/api/content"

VIEW_URL = "https://wiki.host.com/pages/viewpage.action?pageId="

def pprint(data):
    '''
    Pretty prints json data.
    '''
    print json.dumps(
        data,
        sort_keys = True,
        indent = 4,
        separators = (', ', ' : '))


def get_page_id(auth, title):

    url = '{base}?title={title}&spaceKey=Nara&expand=history'.format(
        base = BASE_URL,
        title = title)

    r = requests.get(url, auth = auth)

    #print r

    r.raise_for_status()

    return r.json()

def get_page_info(auth, pageId):

    url = '{base}/{pageId}'.format(
        base = BASE_URL,
        pageId = pageId)

    r = requests.get(url, auth = auth)

#    print r

    r.raise_for_status()

    return r.json()


def write_not_data_avail(auth, html, title):

    info = get_page_id(auth, title)

    pageId = int(info['results'][0]['id'])
    #output = pageId.read()
    print pageId

    write_data_not_null(auth, html, pageId, title)


def write_data_null(auth, html, title):

    spec = 'Prolog'

    data = {
        'type' : 'page',
        'title' : str(title),
        'ancestors' : [{'id' : '46306721'}],
        'space' : {'key' : spec},
        'body'  : {
            'storage' :
            {
                'representation' : 'storage',
                'value' : str(html),
            }
        }
    }

    data = json.dumps(data)

    url = '{base}/'.format(base = BASE_URL)

    r = requests.post(
        url,
        data = data,
        auth = auth,
        headers = { 'Content-Type' : 'application/json' }
    )

    r.raise_for_status()

def execute_funtion_in_order(auth, html, title):

    info = get_page_id(auth, title)
    try:
        write_not_data_avail(auth, html, title)
    except:
        write_data_null(auth, html, title)

def write_data_not_null(auth, html, pageId, title):

    info = get_page_info(auth, pageId)

#    print info

    ver = int(info['version']['number']) + 1


    if title is not None:
        info['title'] = title

    data = {
        'id' : str(pageId),
        'type' : 'page',
        'title' : info['title'],
        'version' : {'number' : ver},
        'body'  : {
            'storage' :
            {
                'representation' : 'storage',
                'value' : str(html),
            }
        }
    }

    data = json.dumps(data)

    url = '{base}/{pageId}'.format(base = BASE_URL, pageId = pageId)

    r = requests.put(
        url,
        data = data,
        auth = auth,
        headers = { 'Content-Type' : 'application/json' }
    )

    r.raise_for_status()

    print "Wrote '%s' version %d" % (info['title'], ver)
    print "URL: %s%d" % (VIEW_URL, pageId)


def get_login(user, passwd):
    '''
    Get the password for username and make auth token.
    '''

    if user is None:
        print 'username is empty'

    if passwd is None:
        print 'password is empty'

    return (user, passwd)


def main():

    parser = argparse.ArgumentParser()

    parser.add_argument(
        "-u",
        "--user",
        default = None,
        help = "Specify the username to log into Confluence")

    parser.add_argument(
        "-p",
        "--passwd",
        default = None,
        help = "Specify the username to log into Confluence")

    parser.add_argument(
        "-t",
        "--title",
        default = None,
        type = str,
        help = "Specify a new title")

    parser.add_argument(
        "-f",
        "--file",
        default = None,
        type = str,
        help = "Write the contents of FILE to the confluence page")

    parser.add_argument(
        "html",
        type = str,
        default = None,
        nargs = '?',
        help = "Write the immediate html string to confluence page")

    options = parser.parse_args()

    auth = get_login(options.user, options.passwd)

    if options.html is not None and options.file is not None:
        raise RuntimeError(
            "Can't specify both a file and immediate html to write to page!")

    if options.html:
        html = options.html

    else:

        with open(options.file, 'r') as fd:
            html = fd.read()

    execute_funtion_in_order(auth, html, options.title)


if __name__ == "__main__" : main()
3
  • Sounds to me like a couple of if... else statements - where's your problem here? Commented May 16, 2017 at 17:11
  • @Jan My problem is if the page exists then it gives me the value and function(write_data_not_null) works fine but if page doesn't exists it doesn't give me null value it gives me error message ""IndexError: list index out of range" and break and doesn't run the other function (write_data_null) Commented May 16, 2017 at 17:14
  • Kind of the same remark as Jan, but if if .. else isn't sufficient for you, what about try .. except? This way if there is a problem your function write_data_null will be call Commented May 16, 2017 at 17:17

2 Answers 2

1

EDIT I just read the comments for your question and updated my response

def write_not_data_avail(auth, html, title):

    info = get_page_id(auth, title)
    try:
        pageId = int(info['results'][0]['id'])
        output = pageId.read()
        print pageId

        info = get_page_info(auth, pageId)

        ver = int(info['version']['number']) + 1

        print ver
        write_data_not_null(auth, html, pageId, title)
    except:
        write_data_null(auth, html, title)

You just need to check the truthiness of pageId since None is considered a false value in Python

Sign up to request clarification or add additional context in comments.

6 Comments

@cmpgmer I am getting this error write_data_null(auth, html, title) NameError: name 'write_data_null' is not defined
Did you define the function write_data_null()? Is it part of a class?
I added my full script in my original post
Make sure you define write_data_null() before you define write_not_data_avail() So all you need to do is move the functions around and it should work.
I am able to fix my problem with creating another function.Thanks for giving me the right direction.I also updated the script in original post
|
0

You could do something like this,

def write_not_data_avail(auth, html, title):

    info = get_page_id(auth, title)
    pageId = int(info['results'][0]['id'])
    output = pageId.read()
    info = get_page_info(auth, pageId)

    ver = int(info['version']['number']) + 1

    try:
        write_data_not_null(auth, html, pageId, title)
    except IndexError:
        write_data_null(auth, html, title)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.