Рендеринг изображения matplotlib в flask - PullRequest
1 голос
/ 05 августа 2020

У меня есть сценарий python, который генерирует изображение для белковых доменов с помощью dna_feature_viewer и отлично работает. Я работаю с flask и хочу отобразить это изображение на веб-странице. введите описание изображения здесь

Прилагаю ниже скрипт:

@app.route('/image' )  
def image():
 d={'domain1': ['4-50'], 'domain2': ['70-100']}
 from Bio import SeqIO
 from Bio.Seq import Seq
 from Bio.SeqRecord import SeqRecord
 from Bio.Alphabet import generic_protein
 from Bio.SeqFeature import SeqFeature, FeatureLocation
 from dna_features_viewer import BiopythonTranslator

 myseq='''MNEGFSEGEMETDRRTCSQQALHKDVEGKERRCQTCRSHLWLVALGLVLLSLTLCIFSLKYFWSPGPRKVYKHQYKVLLD
  GVEMDSVMEIDPNRLMEMFKVGNGSDEVLEVHDFKNGLTGI'''

 sequence_object = Seq(myseq, generic_protein)

 # Create a record
 record = SeqRecord(sequence_object,
               id='123456789', 
               name='Example',
               description='An example ')

 for keys, values in d.items():
   for i in range(len(values)):
      value_split_START=int(values[i].split('-')[0])
      value_split_END=int(values[i].split('-')[1])
      feature = SeqFeature(FeatureLocation(start=value_split_START, end=value_split_END), 
      type=keys)
      record.features.append(feature)


 graphic_record = BiopythonTranslator().translate_record(record)
 ax, _ = graphic_record.plot(figure_width=10, strand_in_label_threshold=7)
 
 image_filename=ax.figure.savefig("static/images/image.png")
 return render_template("image.html", imageout=image_filename)

Скрипт 2. Html скрипт

<img src="{{url_for('static', filename=image_filename )}}" />
   

При запуске скрипта flask он останавливается и показывает следующую ошибку:

WARNING: NSWindow drag regions should only be invalidated on the Main Thread! This will throw an exception in the future. Called from (
0   AppKit                              0x00007fff292cf607 -[NSWindow(NSWindow_Theme) _postWindowNeedsToResetDragMarginsUnlessPostingDisabled] + 378
1   AppKit                              0x00007fff292cc9f7 -[NSWindow _initContent:styleMask:backing:defer:contentView:] + 1479
2   AppKit                              0x00007fff292cc42a -[NSWindow initWithContentRect:styleMask:backing:defer:] + 45
3   _macosx.cpython-37m-darwin.so       0x00000001233d283e -[Window initWithContentRect:styleMask:backing:defer:withManager:] + 94
4   _macosx.cpython-37m-darwin.so       0x00000001233d6745 FigureManager_init + 341
5   python                              0x000000010ed985ac wrap_init + 12
6   python                              0x000000010ed2255e wrapperdescr_call + 254
7   python                              0x000000010ed16ae3 _PyObject_FastCallKeywords + 179
8   python                              0x000000010ee53ed5 call_function + 453
9   python                              0x000000010ee51aec _PyEval_EvalFrameDefault + 46092
10  python                              0x000000010ed168d5 function_code_fastcall + 117
11  python                              0x000000010ed98381 slot_tp_init + 193
12  python                              0x000000010eda2361 type_call + 241
13  python                              0x000000010ed16ae3 _PyObject_FastCallKeywords + 179
14  python                              0x000000010ee53ed5 call_function + 453
15  python                              0x000000010ee51aec _PyEval_EvalFrameDefault + 46092
16  python                              0x000000010ed168d5 function_code_fastcall + 117
17  python                              0x000000010ee53dc7 call_function + 183
18  python                              0x000000010ee51aec _PyEval_EvalFrameDefault + 46092
19  python                              0x000000010ee4549e _PyEval_EvalCodeWithName + 414
20  python                              0x000000010ed15de7 _PyFunction_FastCallDict + 231
21  python                              0x000000010ed19ce2 method_call + 130
22  python                              0x000000010ed17752 PyObject_Call + 130
23  python                              0x000000010ee51d58 _PyEval_EvalFrameDefault + 46712
24  python                              0x000000010ee4549e _PyEval_EvalCodeWithName + 414
25  python                              0x000000010ed15de7 _PyFunction_FastCallDict + 231
26  python                              0x000000010ee51d58 _PyEval_EvalFrameDefault + 46712
27  python                              0x000000010ee4549e _PyEval_EvalCodeWithName + 414
28  python                              0x000000010ed16fe3 _PyFunction_FastCallKeywords + 195
29  python                              0x000000010ee53dc7 call_function + 183
30  python                              0x000000010ee51be0 _PyEval_EvalFrameDefault + 46336
31  python                              0x000000010ee4549e _PyEval_EvalCodeWithName + 414
32  python                              0x000000010ed16fe3 _PyFunction_FastCallKeywords + 195
33  python                              0x000000010ee53dc7 call_function + 183
34  python                              0x000000010ee51be0 _PyEval_EvalFrameDefault + 46336
35  python                              0x000000010ee4549e _PyEval_EvalCodeWithName + 414
36  python                              0x000000010ed15de7 _PyFunction_FastCallDict + 231
37  python                              0x000000010ee51d58 _PyEval_EvalFrameDefault + 46712
38  python                              0x000000010ed168d5 function_code_fastcall + 117
39  python                              0x000000010ee53dc7 call_function + 183
40  python                              0x000000010ee51a56 _PyEval_EvalFrameDefault + 45942
41  python                              0x000000010ed168d5 function_code_fastcall + 117
42  python                              0x000000010ee53dc7 call_function + 183
43  python                              0x000000010ee51a56 _PyEval_EvalFrameDefault + 45942
44  python                              0x000000010ed168d5 function_code_fastcall + 117
45  python                              0x000000010ee53dc7 call_function + 183
46  python                              0x000000010ee51a56 _PyEval_EvalFrameDefault + 45942
47  python                              0x000000010ed168d5 function_code_fastcall + 117
48  python                              0x000000010ed9646d slot_tp_call + 189
49  python                              0x000000010ed16ae3 _PyObject_FastCallKeywords + 179
50  python                              0x000000010ee53ed5 call_function + 453
51  python                              0x000000010ee51aec _PyEval_EvalFrameDefault + 46092
52  python                              0x000000010ed2fe49 gen_send_ex + 169
53  python                              0x000000010ee50c83 _PyEval_EvalFrameDefault + 42403
54  python                              0x000000010ee4549e _PyEval_EvalCodeWithName + 414
55  python                              0x000000010ed16fe3 _PyFunction_FastCallKeywords + 195
56  python                              0x000000010ee53dc7 call_function + 183
57  python                              0x000000010ee51b27 _PyEval_EvalFrameDefault + 46151
58  python                              0x000000010ee4549e _PyEval_EvalCodeWithName + 414
59  python                              0x000000010ed16fe3 _PyFunction_FastCallKeywords + 195
60  python                              0x000000010ee53dc7 call_function + 183
61  python                              0x000000010ee51a56 _PyEval_EvalFrameDefault + 45942
62  python                              0x000000010ed168d5 function_code_fastcall + 117
63  python                              0x000000010ee53dc7 call_function + 183
64  python                              0x000000010ee51a56 _PyEval_EvalFrameDefault + 45942
65  python                              0x000000010ed168d5 function_code_fastcall + 117
66  python                              0x000000010ee53dc7 call_function + 183
67  python                              0x000000010ee51aec _PyEval_EvalFrameDefault + 46092
68  python                              0x000000010ed168d5 function_code_fastcall + 117
69  python                              0x000000010ee53dc7 call_function + 183
70  python                              0x000000010ee51a56 _PyEval_EvalFrameDefault + 45942
71  python                              0x000000010ed168d5 function_code_fastcall + 117
72  python                              0x000000010ed98381 slot_tp_init + 193
73  python                              0x000000010eda2361 type_call + 241
74  python                              0x000000010ed16ae3 _PyObject_FastCallKeywords + 179
75  python                              0x000000010ee53ed5 call_function + 453
76  python                              0x000000010ee51aec _PyEval_EvalFrameDefault + 46092
77  python                              0x000000010ed168d5 function_code_fastcall + 117
78  python                              0x000000010ee53dc7 call_function + 183
79  python                              0x000000010ee51a56 _PyEval_EvalFrameDefault + 45942
80  python                              0x000000010ed168d5 function_code_fastcall + 117
81  python                              0x000000010ed19ce2 method_call + 130
82  python                              0x000000010ed17752 PyObject_Call + 130
83  python                              0x000000010ee51d58 _PyEval_EvalFrameDefault + 46712
84  python                              0x000000010ed168d5 function_code_fastcall + 117
85  python                              0x000000010ee53dc7 call_function + 183
86  python                              0x000000010ee51a56 _PyEval_EvalFrameDefault + 45942
87  python                              0x000000010ed168d5 function_code_fastcall + 117
88  python                              0x000000010ee53dc7 call_function + 183
89  python                              0x000000010ee51a56 _PyEval_EvalFrameDefault + 45942
90  python                              0x000000010ed168d5 function_code_fastcall + 117
91  python                              0x000000010ed19ce2 method_call + 130
92  python                              0x000000010ed17752 PyObject_Call + 130
93  python                              0x000000010ef358cb t_bootstrap + 123
94  python                              0x000000010eebc707 pythread_wrapper + 39
95  libsystem_pthread.dylib             0x00007fff57da22eb _pthread_body + 126
96  libsystem_pthread.dylib             0x00007fff57da5249 _pthread_start + 66
97  libsystem_pthread.dylib             0x00007fff57da140d thread_start + 13

) 127.0.0.1 - - [05 / Aug / 2020 13:46:32] «/ image HTTP / 1.1» 200 - Ошибка утверждения: (NSViewIsCurrentlyBuildingLayerTreeForDisplay ()! = CurrentBuildingLayerTree), функция NSViewSetCurrentlyBuildingLayerTreeForDisplay, файл /BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1671.60.107/AppKit.subproj/NSView.m16, строка 14 * 221 из идей, почему это происходит. Буду очень признателен за любую помощь. Спасибо!

1 Ответ

1 голос
/ 06 августа 2020

Мне не удалось воссоздать это исключение, поэтому я предполагаю, что это может быть что-то специфическое c для вашей среды.

Я тестировал это в официальном образе python docker, работающем внутри Docker Рабочий стол на OSX.

Тем не менее, есть некоторые проблемы с вашим кодом flask, о которых я расскажу здесь. Ближе к концу функции image вам, вероятно, следует сделать что-то вроде:

    # ....
    ax, _ = graphic_record.plot(figure_width=10, strand_in_label_threshold=7)
 
    # This bit changes...

    output_filename = "image.png"
    output_path = os.path.join('static', output_filename)

    # The return value of this is not a filename
    image = ax.figure.savefig(output_path)

    # You should actually be passing `output_filename` to the template
    return render_template("image.html", image_filename=output_filename)

Обратите внимание:

  • output_filename - это фактическое имя файла, которое вы хотите сохранить изображение как
  • output_path - это полный путь static/image.png. Это используется только методом savefig для фактического сохранения файла на диск.
  • Затем мы передаем output_filename в шаблон в качестве аргумента image_filename, который затем становится доступным в шаблоне.

Код шаблона выглядит так:

<img src="{{url_for('static', filename=image_filename )}}" />

Что, в свою очередь, сгенерирует HTML:

<img src="/static/image.png" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...