kerrickstaley / genanki

A Python 3 library for generating Anki decks
MIT License
2.06k stars 161 forks source link

Crash on empty/null field #106

Closed Ambiwlans closed 2 years ago

Ambiwlans commented 2 years ago

This isn't really a bug, mostly my stupidity, but it gives an unhelpful crash during the html entities check if some of the data is blank (or numbers?).

If this isn't changed, it might be worth mentioning in the note pre-processing portion of the tutorial. I just put this in:

str(f or '') for f in [...]

to ensure that Nones are converted to empty strings.

kerrickstaley commented 2 years ago

Could you give an example of some code that triggers this bug?

Ambiwlans commented 2 years ago

The code from the tutorial can cause he crash. It happens when you put null values into notes.

my_deck.add_note(genanki.Note(model=my_model, fields=[blah, bloo])

Where blah is null or maybe just not a string. This causes a crash rather than an error msg.

better code:

my_deck.add_note(genanki.Note(model=my_model, fields=[str(f or '') for f in [blah bloo]]))

I already cleaned up my code (and the database i'm using) so I can't reproduce atm. The crash happens in the _bad_html_entities check

kerrickstaley commented 2 years ago

When I do this, I get a TypeError:

In [4]: my_deck.add_note(genanki.Note(model=my_model, fields=[None, 'bar']))

In [5]: my_deck.write_to_file('/tmp/foo.apkg')
[...]
File ~/src/genanki/genanki/note.py:136, in Note._find_invalid_html_tags_in_field(cls, field)
    134 @classmethod
    135 def _find_invalid_html_tags_in_field(cls, field):
--> 136   return cls._INVALID_HTML_TAG_RE.findall(field)

TypeError: expected string or bytes-like object

I think given this error the user could reasonably be expected to infer that field is None and then go check their code for places where they might be leaving a field as None. I think it adds a lot of code overhead to go through all the places where a user might pass None into the API and pre-emptively check whether they are passing None in order to give nice error messages. So I'm going to close this as won't-fix.