89 lines
3.0 kB
1
defmodule BlogWeb.PythonDemoLive do
2
use BlogWeb, :live_view
3
require Logger
4
5
@impl true
6
def mount(_params, _session, socket) do
7
{:ok, assign(socket,
8
python_result: nil,
9
custom_code: "print('Hello from custom Python code!')",
10
custom_result: nil,
11
error: nil
12
)}
13
end
14
15
@impl true
16
def handle_event("run-hello-world", _params, socket) do
17
# Run the hello world function
18
case Blog.PythonRunner.run_hello_world() do
19
{:ok, result} ->
20
{:noreply, assign(socket, python_result: result, error: nil)}
21
22
{:error, error_msg} ->
23
{:noreply, assign(socket, error: error_msg)}
24
end
25
end
26
27
@impl true
28
def handle_event("run-custom-code", %{"code" => code}, socket) do
29
case Blog.PythonRunner.run_python_code(code) do
30
{:ok, result} ->
31
{:noreply, assign(socket, custom_result: result, error: nil)}
32
33
{:error, error_msg} ->
34
{:noreply, assign(socket, error: error_msg)}
35
end
36
end
37
38
@impl true
39
def render(assigns) do
40
~H"""
41
<div class="mx-auto max-w-3xl p-4">
42
<h1 class="text-2xl font-bold mb-4">Python Interoperability Demo</h1>
43
44
<div class="mb-8 p-4 bg-gray-100 rounded-lg">
45
<h2 class="text-xl font-semibold mb-2">Hello World Example</h2>
46
<p class="mb-4">Run a simple Python "Hello World" program:</p>
47
48
<button phx-click="run-hello-world" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
49
Run Hello World
50
</button>
51
52
<%= if @python_result do %>
53
<div class="mt-4 p-3 bg-white rounded border border-gray-300">
54
<h3 class="font-semibold text-gray-700">Result:</h3>
55
<pre class="mt-2 p-2 bg-gray-50 rounded"><%= @python_result %></pre>
56
</div>
57
<% end %>
58
</div>
59
60
<div class="p-4 bg-gray-100 rounded-lg">
61
<h2 class="text-xl font-semibold mb-2">Custom Python Code</h2>
62
<p class="mb-4">Enter your own Python code to execute:</p>
63
64
<form phx-submit="run-custom-code">
65
<textarea name="code" rows="5" class="w-full p-2 border border-gray-300 rounded mb-4 font-mono"><%= @custom_code %></textarea>
66
67
<button type="submit" class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
68
Execute Code
69
</button>
70
</form>
71
72
<%= if @custom_result do %>
73
<div class="mt-4 p-3 bg-white rounded border border-gray-300">
74
<h3 class="font-semibold text-gray-700">Result:</h3>
75
<pre class="mt-2 p-2 bg-gray-50 rounded"><%= @custom_result %></pre>
76
</div>
77
<% end %>
78
79
<%= if @error do %>
80
<div class="mt-4 p-3 bg-red-100 rounded border border-red-300 text-red-700">
81
<h3 class="font-semibold">Error:</h3>
82
<pre class="mt-2 p-2 bg-red-50 rounded"><%= @error %></pre>
83
</div>
84
<% end %>
85
</div>
86
</div>
87
"""
88
end
89
end
90