2022年8月9日火曜日

Python: Keyを指定して辞書データをソートする

 Keyを指定して辞書データをソートする

test = 
[
    {'name': 'taro', 'age': 18},
    {'name': 'jiro', 'age': 12},
    {'name': 'saburo', 'age': 10}
]
#非破壊的 元のtestはそのまま
sorted_data = sorted(test, key=lambda item: item['age']))
#破壊的 元のtest自体を書き換える
test.sort(key=lambda item: item['age'])
#Result
[
    {'name': 'saburo', 'age': 10},
    {'name': 'jiro', 'age': 12},
    {'name': 'taro', 'age': 18}
]




Python: print関数の結果をファイルに出力する

 print関数の結果をファイルに出力する

with open('file.txt', 'w') as f:
    print('abc', file=f)


2022年8月2日火曜日

Django: Apache (WSGIモジュール) を再起動しなくてもアプリケーション変更を反映させる方法

DjangoをApacheのWSGIで本番運用している場合、アプリケーションプログラムを変更した場合、いちいちApacheを再起動していました。面倒なので簡単に変更が反映される方法がないか調べたところ、

「wsgi.py を微修正して保存する」と変更が反映されることが分かりました。

これで少し楽になりました。

参考
Is it possible to reload the view without restarting Django? - Stack Overflow

https://stackoverflow.com/questions/9183114/is-it-possible-to-reload-the-view-without-restarting-django

If you are running a production server (nginx, apache, etc) and you want code-reload, then you need to add something to your wsgi module to detect code changes.

Code reloading with apache: http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode

Code reloading with uwsgi: http://projects.unbit.it/uwsgi/wiki/TipsAndTricks


If you are running Django as a WSGI application in daemon mode you just need to touch the wsgi.py for your site and it will reload the application next time there is a request. (So no need for any special options).

Django: Admin モデル一覧画面でリストのリンクをすべて無効にする

list_display_links = [] としても、モデルのIDだけが勝手にリンクにされてしまいますが、以下のように None にするとすべて無効化できました。

class TestAdmin(admin.ModelAdmin):

    list_display_links = None #リストのリンクをすべて無効化