pandas MySQL

pandas: MySQL sqlalchemy で mysqlclient を使うには、まず mysqlclient をインストールする必要があります。次に、SQLAlchemy のエンジン構成で mysqlclient を使用するように設定します。以下は、Qiita の記事 ¹ からの例です。 1 2 3 from sqlalchemy import create_engine engine = create_engine('mysql+mysqldb://user:password@host/dbname', echo=True) また、CData Python Connector for MySQL³ を使用することもできます。これは、SQLAlchemy ORM を使用して Python で MySQL データに連携するためのドライバです。 1 2 from sqlalchemy import create_engine engine = create_engine("mysql+mysqlconnector://user:password@host/dbname") どちらの方法でも、SQLAlchemy で MySQL に接続することができます。 ソース: Bing との会話 2023/6/7 (1) 【Python】SQLAlchemy で MySQL に接続する - Qiita. https://qiita.com/curry__30/items/432a21426c02a68e77e8. (2) SQLAlchemy ORM を使って、Python で MySQL データに連携 …. https://www.cdata.com/jp/kb/tech/mysql-python-sqlalchemy.rst. (3) 【Python】SQLAlchemy を試してみる - Qiita. https://qiita.com/ktamido/items/ebdbe5a85dbc3e6004ae. django .env に django の DATABASE_URL が定義されているとする ...

2023年6月7日 · 1 分

django session

Sessionのユーザーの取得 Djangoでセッションレコードがどのユーザーのものかを判定するには、以下のようにします。 1 2 3 4 5 6 7 8 from django.contrib.sessions.models import Session from django.contrib.auth.models import User for session in Session.objects.all(): uid = session.get_decoded().get('_auth_user_id') if uid: user = User.objects.get(id=uid) print(user.username) 参考文献: Django ドキュメント | セッションの使いかた ソース: Bing との会話 2023/5/30 (1) セッションの使いかた | Django ドキュメント | Django. https://docs.djangoproject.com/ja//2.2/topics/http/sessions/. (2) 【Django】ログイン判定機能の実装方法を実例付きで徹底解説. https://itc.tokyo/django/dynamic-links-by-user-info/. (3) Djangoで現在ログインしているユーザーのユーザーIDを取得する方法. https://qastack.jp/programming/12615154/how-to-get-the-currently-logged-in-users-user-id-in-django. SessionStoreをつかう 1 2 3 4 5 6 7 from django.contrib.sessions.backends.db import SessionStore key = "3gsbhdfm4g2uyyieaaxl1omor2p5f1on" store = SessionStore(session_key=key) store["ssout_required"] = True store.save()

2023年5月30日 · 1 分

django-import-export

django-import-export django-import-export = "^2.4.0" settings.py 1 2 3 4 5 INSTALLED_APPS += [ ... "import_export", ... ] resources.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from import_export import resources from .. import models class DepartmentResource(resources.ModelResource): class Meta: model = models.Department import_id_fields = ["code", "company_code"] # 複合キー exclude = ["company", "jobposts", "origin", "status"] # 除外 def get_instance(self, instance_loader, row): instance = super().get_instance(instance_loader, row) exclude = [] if instance: exclude += ["is_m03", "is_tmb"] # 更新除外 list(map(lambda i: row.pop(i, None), exclude)) return instance admin.py 1 2 3 4 5 6 7 8 9 10 11 12 13 from import_export.admin import ImportExportActionModelAdmin from . import inlines, resources class BaseModelAdmin(ImportExportActionModelAdmin): exclude = ["created_at"] readonly_fields = ["updated_at"] @admin.register(models.Department) class DepartmentAdmin(BaseModelAdmin): ... resource_class = resources.DepartmentResource

2023年5月18日 · 1 分

Django Subquery

Subquery 合計値のアノテート サブクエリの合計値: 合計対象レコードを OuterRefで条件指定してして絞り込む values() で ユニークフィールドで GROUP BY する 対象フィールドの合計値をanotate する アノテートしたフィールドを values() で ValueList にしてSubqueryで返す(1件のはず) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 def verify(): from django.db.models import OuterRef, Subquery, F from django.db.models.functions import Coalesce from base.models.utils import aggr_sum_decimal as D from decimal import Decimal ref_query = dict( book__company_code=OuterRef("company_code"), book__processing_month=OuterRef("processing_month"), account_code=OuterRef("account_code"), account_item_code=OuterRef("account_item_code"), advances_code=OuterRef("outsource_code"), advances_branch_code=OuterRef("outsource_branch_code"), ) def bookitem_sum(bookitem): qs = ( bookitem.objects.filter(**ref_query) .values(*ref_query.keys()) .annotate(total=D("amount")) .values("total") ) return Subquery(qs) qs = models.CostOutsource.objects.annotate( sum_debit=Coalesce(bookitem_sum(BookDebit), Decimal("0")), sum_credit=Coalesce(bookitem_sum(BookCredit), Decimal("0")), ).exclude(debit_amount=F("sum_debit"), credit_amount=F("sum_credit")) Bing Djangoのクエリセットで、別のテーブルのフィールドの合計値をSubqueryを使ってannotateすることができます¹。以下は、例です。 ...

2023年5月17日 · 1 分

DRF: Content Negotiation

DRF: Content Negotiation DefaultContentNegotiation content_negotiation_classをカスタマイズするには、以下のようにします。 1 2 3 4 5 6 from rest_framework.negotiation import DefaultContentNegotiation class MyContentNegotiation(DefaultContentNegotiation): def select_renderer(self, request, renderers, format_suffix=None): # ここに処理を書きます。 pass 上記の例では、DefaultContentNegotiationを継承しています。 select_renderer()メソッドには、レンダラーを選択するための処理を書きます。 このメソッドは、リクエストオブジェクト、レンダラーのリスト、およびフォーマットサフィックスを引数として受け取ります。 ソース: Bing との会話 2023/5/12 (1) Content negotiation - Django REST framework. https://www.django-rest-framework.org/api-guide/content-negotiation/. (2) Django REST Framework - Content negotiation - HTTPは …. https://runebook.dev/ja/docs/django_rest_framework/api-guide/content-negotiation/index. (3) Django REST framework カスタマイズ方法 - チュートリアルの補足. https://qiita.com/okoppe8/items/c58bb3faaf26c9e2f27f. ViewSetでの設定 ViewSetごとにcontent_negotiation_classを設定することができます。 ...

2023年5月12日 · 1 分

jupyter: Django

Jupyter: Django 準備 django_extensions , notebookを入れておく settgins.py: 1 INSTALLED_APPS += ['django_extensions'] VSCode VSCodeでJupyterのPythonランタイムを選んでから以下を実行する 環境変数で、DJANGO_ALLOW_ASYNC_UNSAFE=true をセットしておく(.envとか) 1 2 3 4 5 6 import sys, os, django BASE_DIR = "path_ot_manage_py" sys.path.insert(0, BASE_DIR) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") django.setup() リモートサーバー autossh でポートフォワード PCの 8.8.8.8 -> リモート(EC2とか)の 8.8.8.8 にフォワードする: 1 autossh -M 0 -F .secrets/ssh.ec2.conf server -N -L 8888:localhost:8888 -4 カーネル起動 1 DJANGO_ALLOW_ASYNC_UNSAFE=true python manage.py shell_plus --notebook URLが表示されるので、ブラウザでアクセスする ...

2023年5月5日 · 1 分

redis

redis Ubuntu 1 sudo apt update && sudo apt install redis-server -y 1 2 $ ps ax | grep redis 1083463 ? Ssl 0:00 /usr/bin/redis-server 127.0.0.1:6379 redis-cli redis-cliコマンドでデータベース1に接続するには、次のように入力します。¹² redis-cli -n 1 このコマンドは、データベース1に接続するためのものです。-nオプションを使用して、データベース番号を指定します。 上記の例では、データベース番号が1であることを示しています。 ソース: Bing との会話 2023/5/5 (1) redis-cliの接続時によく使うコマンド使い方メモ - Qiita. https://qiita.com/a-nishimura/items/54b0d85dbce47685a36f. (2) 【入門】Redis - Qiita. https://qiita.com/wind-up-bird/items/f2d41d08e86789322c71. (3) redis-cliの使い方 - Qiita. https://qiita.com/sawada_masahiko/items/1f60936c421ecab8dfbf. (4) redis-cliでよく使うコマンド20選 - Qiita. https://qiita.com/hatsu/items/a52817364160e0b6bb60. (5) Redisコマンド一覧 - Qiita. https://qiita.com/taiba/items/18016906d80c13e88853. (6) リモート環境にあるRedisに接続する - 箱のプログラミング日記。. https://www.y-hakopro.com/entry/2020/10/31/185235. Django 1 poetry add django-redis settings.py: ...

2023年5月5日 · 1 分

djang-mptt: tree 構造で export する

django-mptt: Tree モデルを エクスポート mptt_tags テンプレートライブラリ の recursetree / endrecursetree タグを使う profiles/templates/profile/workgroup/tree.json: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 {% load mptt_tags %} [ {% recursetree nodes %} { "id": "{{ node.id }}", "code": "{{ node.code|default:''}}", "name": "{{ node.name }}", "path": "{{ node.path }}", "full_name": "{{ node.full_name }}", "data": {}, "children": [{{ children }}] }{% if node.get_next_sibling %},{% endif %} {% endrecursetree %} ] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 from django.template import engines, loader from django.utils.safestring import mark_safe from django.db.models import QuerySet def render(src, request=None, engine_name="django", safe=True, **ctx): text = engines[engine_name].from_string(src).render(ctx, request=request) return safe and mark_safe(text) or text def render_by(name, request=None, safe=True, **ctx): t = loader.get_template(name) text = t.render(ctx, request=request) return safe and mark_safe(text) or text def export_trees(nodes, model_class=None, template_name=None, request=None, safe=True, **ctx): if not model_class and isinstance(nodes, QuerySet): model_class = nodes.model if not template_name and model_class: template_name = f"{model_class._meta.app_label}/{model_class._meta.model_name}/tree.json" if not template_name: return "" return render_by(template_name, request=request, safe=safe, nodes=nodes, **ctx) 1 2 3 4 5 6 7 8 @main.command() @click.argument("path") @click.pass_context def workgroup_export(ctx, path): """ Workgroup Export """ nodes = models.Workgroup.objects.all() print(export_trees(nodes))

2023年5月4日 · 1 分

Django: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async

Jupyter: Django: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async このエラーは、asyncコンテキストから同期的なコードを呼び出そうとした場合に発生するエラーです。 async-unsafeなコードを呼び出す場合は、asyncコンテキストからではなく、自分自身の同期関数で書き、それをasgiref.sync.syncを使用して呼び出すように修正する必要があります¹。 ¹: Django: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. - Stack Overflow ソース: Bing との会話 2023/5/4 (1) Django: SynchronousOnlyOperation: You cannot call this …. https://stackoverflow.com/questions/61926359/django-synchronousonlyoperation-you-cannot-call-this-from-an-async-context-u. (2) django.core.exceptions.SynchronousOnlyOperation after …. https://github.com/django/channels/issues/1464. (3) python - Django channels Async Websocket throwing Error …. https://stackoverflow.com/questions/63892884/django-channels-async-websocket-throwing-error-while-trying-to-use-database-quer. (4) Django channel occasionally gets error “cannot call this from …. https://stackoverflow.com/questions/69239657/django-channel-occasionally-gets-error-cannot-call-this-from-an-async-context. (5) python - Getting SynchronousOnlyOperation error Even after …. https://stackoverflow.com/questions/63149616/getting-synchronousonlyoperation-error-even-after-using-sync-to-async-in-django. DJANGO_ALLOW_ASYNC_UNSAFE 環境変数を使用することで、非同期コンテキストで SynchronousOnlyOperation エラーが発生した場合に警告を無効にすることができます¹。 ...

2023年5月4日 · 1 分

factory_boy: SubFactory

factory_boy: SubFuctory で ForeignKeyフィールドを初期化する factory_boy はテストデータを簡単に作るためのライブラリです²。ForeignKey フィールドのインスタンスのデフォルトを定義するには、SubFactory を使う方法があります¹⁴。例えば、以下のように書けます。 1 2 3 4 5 6 7 8 class PhoneContactFactory(factory.django.DjangoModelFactory): class Meta: model = models.PhoneContact class CoopFactory(factory.django.DjangoModelFactory): class Meta: model = models.Coop phone = factory.SubFactory(PhoneContactFactory) この場合、CoopFactory を使って Coop インスタンスを作ると、PhoneContactFactory も使って PhoneContact インスタンスを作り、そのインスタンスを Coop の phone フィールドにセットします。 もしくは、SelfAttribute を使う方法もあります⁴。例えば、以下のように書けます。 1 2 3 4 5 6 7 8 class SubtitlesFactory(factory.django.DjangoModelFactory): class Meta: model = models.Subtitles class RecordingFactory(factory.django.DjangoModelFactory): class Meta: model = models.Recording subtitles = factory.SubFactory(SubtitlesFactory, language=factory.SelfAttribute('..language')) この場合、RecordingFactory を使って Recording インスタンスを作るときに language パラメータを指定すると、その値が SubtitlesFactory の language パラメータにも渡されます。 ...

2023年4月30日 · 2 分