LoginSignup
7
8

More than 5 years have passed since last update.

[Python] 自作のcsvファイル解析モジュールをwebアプリに組み込むためのシンプルなサンプル

Posted at

この記事について

Djangoのサンプルコードです。

機械学習等でcsvファイルを読み込んで解析を行うモジュールを作ることがあるかと思います。ちょっと作ったモジュールをwebアプリに組み込んでブラウザで試してみたい時に使ってください。

すぐ使えるのはこちら。

使い方はREAD.ME 参照。CSVのデータをデータベースに投入し、Django REST FrameworkとJavaScriptでグラフを描くなんてのも面白いので是非やってみてください。

参考

サンプルコード

urls.py
from django.urls import path
from .views import UploadView


urlpatterns = [
    path('', UploadView.as_view(), name='index'),
]
forms.py
from django import forms
from django.core.validators import FileExtensionValidator


class UploadForm(forms.Form):
    file = forms.FileField(
        validators=[FileExtensionValidator(['csv', ])])
views.py
import csv
import io

from django.http import HttpResponse
from django.views.generic import FormView

from .forms import UploadForm


# Create your views here.
class UploadView(FormView):
    form_class = UploadForm
    template_name = 'app/UploadForm.html'

    def form_valid(self, form):
        csvfile = io.TextIOWrapper(form.cleaned_data['file'])

        # この部分をあなたのコードに差し替えます。
        reader = csv.reader(csvfile)
        count = sum(1 for row in reader)
        result = 'データ件数は{}件です'.format(count)

        # 結果をブラウザに表示させたいときはこちら
        return self.render_to_response(self.get_context_data(result=result))

        # 結果をテキストファイルでダウンロードさせたいときはこちら
        # response = HttpResponse(result, content_type='text/plain')
        # response['Content-Disposition'] = 'attachment; filename = "result.txt"'
        # return response
UploadForm.html
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<div>
    <form action="{% url 'index' %}" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <div>
            <div>
                {{ form.file }}
                <p>{{ form.file.errors }}</p>
            </div>
        </div>
        <input type="submit" value="アップロード">
    </form>
    <pre>{{ result }}</pre>
</div>
</div>
</body>
</html>

7
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8