mirror of
https://github.com/GSA/notifications-admin.git
synced 2026-02-07 11:53:52 -05:00
We require users to export their spreadsheets as CSV files before uploading them. But this seems like the sort of thing a computer should be able to do. So this commit adds a wrapper class which: - takes a the uploaded file - returns it in a normalised format, or reads it using pyexcel[1] - gives the data back in CSV format This allows us to accept `.csv`, `.xlsx`, `.xls` (97 and 95), `.ods`, `.xlsm` and `.tsv` files. We can upload the resultant CSV just like normal, and process it for errors as before. Testing --- To test this I’ve added a selection of common spreadsheet files as test data. They all contain the same data, so the tests look to see that the resultant CSV output is the same for each. UI changes --- This commit doesn’t change the UI, apart from to give a different error message if a user uploads a file type that we still don’t understand. I intend to do this as a separate pull request, in order to fulfil https://www.pivotaltracker.com/story/show/119371637
50 lines
1.6 KiB
Python
50 lines
1.6 KiB
Python
import re
|
||
from wtforms import ValidationError
|
||
from notifications_utils.template import Template
|
||
from app.utils import Spreadsheet
|
||
|
||
|
||
class Blacklist(object):
|
||
def __init__(self, message=None):
|
||
if not message:
|
||
message = 'Password is blacklisted.'
|
||
self.message = message
|
||
|
||
def __call__(self, form, field):
|
||
if field.data in ['password1234', 'passw0rd1234']:
|
||
raise ValidationError(self.message)
|
||
|
||
|
||
class CsvFileValidator(object):
|
||
|
||
def __init__(self, message='Not a csv file'):
|
||
self.message = message
|
||
|
||
def __call__(self, form, field):
|
||
if not Spreadsheet.can_handle(field.data.filename):
|
||
raise ValidationError("{} isn’t a spreadsheet that Notify can read".format(field.data.filename))
|
||
|
||
|
||
class ValidEmailDomainRegex(object):
|
||
|
||
def __call__(self, form, field):
|
||
from flask import (current_app, url_for)
|
||
message = (
|
||
'Enter a central government email address.'
|
||
' If you think you should have access'
|
||
' <a href="{}">contact us</a>').format(url_for('main.feedback'))
|
||
valid_domains = current_app.config.get('EMAIL_DOMAIN_REGEXES', [])
|
||
email_regex = "[^\@^\s]+@([^@^\\.^\\s]+\.)*({})$".format("|".join(valid_domains))
|
||
if not re.match(email_regex, field.data.lower()):
|
||
raise ValidationError(message)
|
||
|
||
|
||
class NoCommasInPlaceHolders():
|
||
|
||
def __init__(self, message='You can’t have commas in your fields'):
|
||
self.message = message
|
||
|
||
def __call__(self, form, field):
|
||
if ',' in ''.join(Template({'content': field.data}).placeholders):
|
||
raise ValidationError(self.message)
|