-
Notifications
You must be signed in to change notification settings - Fork 14.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Import CSV #3643
Merged
Merged
Import CSV #3643
Changes from 6 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
846cc74
add upload csv button to sources dropdown
timifasubaa 7e4f1d7
upload csv to non-hive datasources
timifasubaa ac790c0
upload csv to hive datasource
timifasubaa f352e9d
update FAQ page
timifasubaa abd6ba1
add tests
timifasubaa abdca6f
fix linting errors and merge conflicts
timifasubaa f854b10
Merge branch 'master' into import_csv
timifasubaa 0469d84
Merge branch 'master' into import_csv
timifasubaa 80cead5
Update .travis.yml
timifasubaa ba08a1d
Update tox.ini
timifasubaa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,21 +17,30 @@ | |
from __future__ import unicode_literals | ||
|
||
from collections import defaultdict, namedtuple | ||
import csv | ||
import inspect | ||
import logging | ||
import os | ||
import re | ||
import textwrap | ||
import time | ||
|
||
import boto3 | ||
from flask import g | ||
from flask_babel import lazy_gettext as _ | ||
import pandas | ||
from sqlalchemy import select | ||
from sqlalchemy.engine import create_engine | ||
from sqlalchemy.engine.url import make_url | ||
from sqlalchemy.sql import text | ||
import sqlparse | ||
from werkzeug.utils import secure_filename | ||
|
||
from superset import cache_util, conf, utils | ||
from superset import app, cache_util, conf, db, utils | ||
from superset.utils import QueryStatus, SupersetTemplateException | ||
|
||
config = app.config | ||
|
||
tracking_url_trans = conf.get('TRACKING_URL_TRANSFORMER') | ||
|
||
Grain = namedtuple('Grain', 'name label function') | ||
|
@@ -73,6 +82,66 @@ def extra_table_metadata(cls, database, table_name, schema_name): | |
"""Returns engine-specific table metadata""" | ||
return {} | ||
|
||
@staticmethod | ||
def csv_to_df(**kwargs): | ||
kwargs['filepath_or_buffer'] = \ | ||
app.config['UPLOAD_FOLDER'] + kwargs['filepath_or_buffer'] | ||
kwargs['encoding'] = 'utf-8' | ||
kwargs['iterator'] = True | ||
chunks = pandas.read_csv(**kwargs) | ||
df = pandas.DataFrame() | ||
df = pandas.concat(chunk for chunk in chunks) | ||
return df | ||
|
||
@staticmethod | ||
def df_to_db(df, table, **kwargs): | ||
df.to_sql(**kwargs) | ||
table.user_id = g.user.id | ||
table.schema = kwargs['schema'] | ||
table.fetch_metadata() | ||
db.session.add(table) | ||
db.session.commit() | ||
|
||
@staticmethod | ||
def create_table_from_csv(form, table): | ||
def allowed_file(filename): | ||
# Only allow specific file extensions as specified in the config | ||
extension = os.path.splitext(filename)[1] | ||
return extension and extension[1:] in app.config['ALLOWED_EXTENSIONS'] | ||
|
||
filename = secure_filename(form.csv_file.data.filename) | ||
if not allowed_file(filename): | ||
return (False, 'Invalid file type selected.') | ||
kwargs = { | ||
'filepath_or_buffer': filename, | ||
'sep': form.sep.data, | ||
'header': form.header.data if form.header.data else 0, | ||
'index_col': form.index_col.data, | ||
'mangle_dupe_cols': form.mangle_dupe_cols.data, | ||
'skipinitialspace': form.skipinitialspace.data, | ||
'skiprows': form.skiprows.data, | ||
'nrows': form.nrows.data, | ||
'skip_blank_lines': form.skip_blank_lines.data, | ||
'parse_dates': form.parse_dates.data, | ||
'infer_datetime_format': form.infer_datetime_format.data, | ||
'chunksize': 10000, | ||
} | ||
df = BaseEngineSpec.csv_to_df(**kwargs) | ||
|
||
df_to_db_kwargs = { | ||
'table': table, | ||
'df': df, | ||
'name': form.name.data, | ||
'con': create_engine(form.con.data, echo=False), | ||
'schema': form.schema.data, | ||
'if_exists': form.if_exists.data, | ||
'index': form.index.data, | ||
'index_label': form.index_label.data, | ||
'chunksize': 10000, | ||
} | ||
BaseEngineSpec.df_to_db(**df_to_db_kwargs) | ||
return (True, '') | ||
|
||
@classmethod | ||
def escape_sql(cls, sql): | ||
"""Escapes the raw SQL""" | ||
|
@@ -717,6 +786,51 @@ def fetch_result_sets(cls, db, datasource_type, force=False): | |
return BaseEngineSpec.fetch_result_sets( | ||
db, datasource_type, force=force) | ||
|
||
@staticmethod | ||
def create_table_from_csv(form, table): | ||
"""Uploads a csv file and creates a superset datasource in Hive.""" | ||
def get_column_names(filepath): | ||
with open(filepath, 'rb') as f: | ||
return csv.reader(f).next() | ||
|
||
table_name = form.name.data | ||
filename = form.csv_file.data.filename | ||
|
||
bucket_path = app.config['CSV_TO_HIVE_UPLOAD_BUCKET'] | ||
|
||
if not bucket_path: | ||
logging.info('No upload bucket specified') | ||
return ( | ||
False, | ||
'No upload bucket specified. You can specify one in the config file.') | ||
|
||
upload_prefix = app.config['CSV_TO_HIVE_UPLOAD_DIRECTORY'] | ||
dest_path = os.path.join(table_name, filename) | ||
|
||
upload_path = app.config['UPLOAD_FOLDER'] + \ | ||
secure_filename(form.csv_file.data.filename) | ||
column_names = get_column_names(upload_path) | ||
schema_definition = ', '.join( | ||
[s + ' STRING ' for s in column_names]) | ||
|
||
s3 = boto3.client('s3') | ||
location = os.path.join('s3a://', bucket_path, upload_prefix, table_name) | ||
s3.upload_file( | ||
upload_path, 'airbnb-superset', | ||
os.path.join(upload_prefix, table_name, filename)) | ||
sql = """CREATE EXTERNAL TABLE {table_name} ( {schema_definition} ) | ||
ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS | ||
TEXTFILE LOCATION '{location}'""".format(**locals()) | ||
try: | ||
logging.info(form.con.data) | ||
engine = create_engine(form.con.data) | ||
engine.execute(sql) | ||
return (True, '') | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It seems more Pythonic to return a scalar and raise an exception in the case of the failure. |
||
except Exception as e: | ||
logging.exception(e) | ||
logging.info(sql) | ||
return (False, BaseEngineSpec.extract_error_message(e)) | ||
|
||
@classmethod | ||
def convert_dttm(cls, target_type, dttm): | ||
tt = target_type.upper() | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
"""Contains the logic to create cohesive forms on the explore view""" | ||
from __future__ import absolute_import | ||
from __future__ import division | ||
from __future__ import print_function | ||
from __future__ import unicode_literals | ||
|
||
from flask_appbuilder.fieldwidgets import BS3TextFieldWidget | ||
from flask_appbuilder.forms import DynamicForm | ||
from flask_babel import lazy_gettext as _ | ||
from flask_wtf.file import FileAllowed, FileField, FileRequired | ||
from wtforms import ( | ||
BooleanField, IntegerField, SelectField, StringField) | ||
from wtforms.validators import DataRequired, NumberRange, Optional | ||
|
||
from superset import app | ||
|
||
config = app.config | ||
|
||
|
||
class CsvToDatabaseForm(DynamicForm): | ||
name = StringField( | ||
_('Table Name'), | ||
description=_('Name of table to be created from csv data.'), | ||
validators=[DataRequired()], | ||
widget=BS3TextFieldWidget()) | ||
csv_file = FileField( | ||
_('CSV File'), | ||
description=_('Select a CSV file to be uploaded to a database.'), | ||
validators=[ | ||
FileRequired(), FileAllowed(['csv'], _('CSV Files Only!'))]) | ||
|
||
con = SelectField( | ||
_('Database'), | ||
description=_('database in which to add above table.'), | ||
validators=[DataRequired()], | ||
choices=[]) | ||
sep = StringField( | ||
_('Delimiter'), | ||
description=_('Delimiter used by CSV file (for whitespace use \s+).'), | ||
validators=[DataRequired()], | ||
widget=BS3TextFieldWidget()) | ||
if_exists = SelectField( | ||
_('Table Exists'), | ||
description=_( | ||
'If table exists do one of the following: ' | ||
'Fail (do nothing), Replace (drop and recreate table) ' | ||
'or Append (insert data).'), | ||
choices=[ | ||
('fail', _('Fail')), ('replace', _('Replace')), | ||
('append', _('Append'))], | ||
validators=[DataRequired()]) | ||
|
||
schema = StringField( | ||
_('Schema'), | ||
description=_('Specify a schema (if database flavour supports this).'), | ||
validators=[Optional()], | ||
widget=BS3TextFieldWidget(), | ||
filters=[lambda x: x or None]) | ||
header = IntegerField( | ||
_('Header Row'), | ||
description=_( | ||
'Row containing the headers to use as ' | ||
'column names (0 is first line of data). ' | ||
'Leave empty if there is no header row.'), | ||
validators=[Optional()], | ||
widget=BS3TextFieldWidget(), | ||
filters=[lambda x: x or None]) | ||
index_col = IntegerField( | ||
_('Index Column'), | ||
description=_( | ||
'Column to use as the row labels of the ' | ||
'dataframe. Leave empty if no index column.'), | ||
validators=[Optional(), NumberRange(0, 1E+20)], | ||
widget=BS3TextFieldWidget(), | ||
filters=[lambda x: x or None]) | ||
mangle_dupe_cols = BooleanField( | ||
_('Mangle Duplicate Columns'), | ||
description=_('Specify duplicate columns as "X.0, X.1".')) | ||
skipinitialspace = BooleanField( | ||
_('Skip Initial Space'), | ||
description=_('Skip spaces after delimiter.')) | ||
skiprows = IntegerField( | ||
_('Skip Rows'), | ||
description=_('Number of rows to skip at start of file.'), | ||
validators=[Optional(), NumberRange(0, 1E+20)], | ||
widget=BS3TextFieldWidget(), | ||
filters=[lambda x: x or None]) | ||
nrows = IntegerField( | ||
_('Rows to Read'), | ||
description=_('Number of rows of file to read.'), | ||
validators=[Optional(), NumberRange(0, 1E+20)], | ||
widget=BS3TextFieldWidget(), | ||
filters=[lambda x: x or None]) | ||
skip_blank_lines = BooleanField( | ||
_('Skip Blank Lines'), | ||
description=_( | ||
'Skip blank lines rather than interpreting them ' | ||
'as NaN values.')) | ||
parse_dates = BooleanField( | ||
_('Parse Dates'), | ||
description=_('Parse date values.')) | ||
infer_datetime_format = BooleanField( | ||
_('Infer Datetime Format'), | ||
description=_( | ||
'Use Pandas to interpret the datetime format ' | ||
'automatically.')) | ||
decimal = StringField( | ||
_('Decimal Character'), | ||
description=_('Character to interpret as decimal point.'), | ||
validators=[Optional()], | ||
widget=BS3TextFieldWidget(), | ||
filters=[lambda x: x or '.']) | ||
index = BooleanField( | ||
_('Dataframe Index'), | ||
description=_('Write dataframe index as a column.')) | ||
index_label = StringField( | ||
_('Column Label(s)'), | ||
description=_( | ||
'Column label for index column(s). If None is given ' | ||
'and Dataframe Index is True, Index Names are used.'), | ||
validators=[Optional()], | ||
widget=BS3TextFieldWidget(), | ||
filters=[lambda x: x or None]) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit. Rename
allowed_file
to _allowed_file`.