Search code examples
pythonbeautifulsoupweb2py

web2py button should do different things


I'm new to web2py and websites in general. I would like to upload xml-files with different numbers of questions in it. I'm using bs4 to parse the uploaded file and then I want to do different things: if there is only one question in the xml file I would like to go to a new site and if there are more questions in it I want to go to another site. So this is my code:

def import_file():
form = SQLFORM.factory(Field('file','upload', requires = IS_NOT_EMPTY(), uploadfolder = os.path.join(request.folder, 'uploads'), label='file:'))
if form.process().accepted:
    soup = BeautifulSoup('file', 'html.parser')
    questions = soup.find_all(lambda tag:tag.name == "question" and tag["type"] != "category")
    # now I want to check the length of the list to redirect to the different URL's, but it doesn't work, len(questions) is 0.
    if len(questions) == 1:
        redirect(URL('import_questions'))
    elif len(questions) > 1:
        redirect(URL('checkboxes'))
return dict(form=form, message=T("Please upload the file"))

Does anybody know what I can do, to check the length of the list, after uploading the xml-file?


Solution

  • BeautifulSoup expects a string or a file-like object, but you're passing 'file'. Instead, you should use:

    with open(form.vars.file) as f:
        soup = BeautifulSoup(f, 'html.parser')
    

    However this is not a web2py-specific problem.

    Hope this helps.