pythonbibtexfileparsing

How to use the biblib parser with a bibtex file stored in a pyhon variable?


I have a bibtex file that I get from the frontend and I'm trying to parse this file with biblib (a python library to parse bibtex files). Because I get the file from the frontend its not stored in a file on my computer. The file gets passed through a variable from the frontend to python and is then stored in the python variable fileFromFrontend. So I can use for example:

bibtexFile = fileFromFrontend.read() to read the file.

now I'm trying to do something like the following to print the parsed file in the python terminal:

from pybtex.database.input import bibtex

parser = bibtex.Parser()
bibtexFile= parser.parse_file(fileFromFrontend)
print (bibtexFile.entries)

but then I get this error:

-->bibtexFile = parser.parse_file(filesFromFrontend)
-->with open_file(filename, encoding=self.encoding) as f:
-->AttributeError: __enter__

This is probably because the parser tries to open the file but he doesn't have to open this file, he just needs to read this file. I don't know what function of the biblib library to use for parsing the file from a variable and haven't found anything so far to solve my problem.

Hopefully somebody can help

thanks


Solution

  • According to documentation ( https://docs.pybtex.org/api/parsing.html ) there is methods

    parse_string and parse_bytes which could work.

    so like this

    from pybtex.database.input import bibtex
    
    parser = bibtex.Parser()
    bibtexFile= parser.parse_bytes(fileFromFrontend.read())   
    print (bibtexFile.entries)
    

    I don't have pybtex installed, so I couldn't try it myself. But try those methods. Parse_bytes and parse_string needs bib-format as second parameter. In examples that is bibtex, so I tried it here.