Ссылка на изображение веб-сервера на Pi для разных URL-адресов

Я создаю веб-сервер на модели raspberry pi 3b+ для управления вводом/выводом контактов через веб-сайт. Я использую python/flask в качестве серверной части.

Веб-сайт выглядит хорошо, когда я захожу на IP-адрес 192.168.147.246.

Однако, как только я нажимаю кнопку, чтобы открыть/закрыть. Логотип исчезает, потому что URL больше не просто IP-адрес 192.168.147.246, теперь это 192.168.147.246/pinnumber/command (т.е. 192.168.147.246/4/open).

номер контакта = контакт, который был подключен команда = открыть/закрыть

Вопрос в том, «как сделать так, чтобы изображение появлялось, а стиль оставался, даже если URL-адрес изменяется в зависимости от действий пользователя?»

Вот используемый код Python:

import RPi.GPIO as GPIO
from flask import Flask, render_template, request
app = Flask(__name__)
GPIO.setmode(GPIO.BCM)

# Create a dictionary called pins to store the pin number, name, and pin state:
pins = {
   4 : {'name' : 'Airport Box 1', 'state' : GPIO.LOW},
   24 : {'name' : 'Airport Box 2', 'state' : GPIO.LOW}
   }

# Set each pin as an output and make it low:
for pin in pins:
   GPIO.setup(pin, GPIO.OUT)
   GPIO.output(pin, GPIO.HIGH)

@app.route("/")
def main():
   # For each pin, read the pin state and store it in the pins dictionary:
   for pin in pins:
      pins[pin]['state'] = GPIO.input(pin)
   # Put the pin dictionary into the template data dictionary:
   templateData = {
      'pins' : pins
      }
   # Pass the template data into the template main.html and return it to the user
   return render_template('index.html', **templateData)

# The function below is executed when someone requests a URL with the pin number and action in it:
@app.route("/<changePin>/<action>")
def action(changePin, action):
   # Convert the pin from the URL into an integer:
   changePin = int(changePin)
   # Get the device name for the pin being changed:
   deviceName = pins[changePin]['name']
   # If the action part of the URL is "on," execute the code indented below:
   if action == "close":
      # Set the pin high:
      GPIO.output(changePin, GPIO.HIGH)
      # Save the status message to be passed into the template:
      message = "Turned " + deviceName + " close"
   if action == "open":
      GPIO.output(changePin, GPIO.LOW)
      message = "Turned " + deviceName + " open."

   # For each pin, read the pin state and store it in the pins dictionary:
   for pin in pins:
      pins[pin]['state'] = GPIO.input(pin)

   # Along with the pin dictionary, put the message into the template data dictionary:
   templateData = {
      'pins' : pins
   }

   return render_template('index.html', **templateData)

if __name__ == "__main__":
   app.run(host='0.0.0.0', port=80, debug=True)

Это html-код:

<!DOCTYPE html>
    <head>
        <title> {{Title}} </title>
	<!-- Latest compiled and minified CSS -->
  	<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity = "sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin = "anonymous">
  		<!-- Optional theme -->
  	<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity = "sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin = "anonymous">
  	<link rel = "stylesheet" href = "static/style.css/">
    </head>
      

<body>
<h1> <img src = "static/logo.png" alt = "logo"> Name </h1>

    <h3> Check in Area A </h3>
    {% for pin in pins %}
    <h3>{{ pins[pin].name }}
      {% if pins[pin].state == true %}
      is currently closed</h3>
    <div class = "row">
      <div class = "col-md-2">
        <a href = "/{{pin}}/open" class = "btn btn-block btn-lg btn-default" role = "button">Open Box</a>
      </div>
    </div>
    {% else %}
    is currently opened</h3>
    <div class = "row">
      <div class = "col-md-2">
        <a href = "/{{pin}}/close" id = "closeBTN" class = "btn btn-block btn-lg btn-primary" role = "button">Close Box</a></div>
    </div>
    {% endif %}
    {% endfor %}

<p> <strong> Email: xxxxx </strong> </p>	
 </body>
 
 </html>	
Почему в Python есть оператор "pass"?
Почему в Python есть оператор "pass"?
Оператор pass в Python - это простая концепция, которую могут быстро освоить даже новички без опыта программирования.
Некоторые методы, о которых вы не знали, что они существуют в Python
Некоторые методы, о которых вы не знали, что они существуют в Python
Python - самый известный и самый простой в изучении язык в наши дни. Имея широкий спектр применения в области машинного обучения, Data Science,...
Основы Python Часть I
Основы Python Часть I
Вы когда-нибудь задумывались, почему в программах на Python вы видите приведенный ниже код?
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
Алиса и Боб имеют неориентированный граф из n узлов и трех типов ребер:
Оптимизация кода с помощью тернарного оператора Python
Оптимизация кода с помощью тернарного оператора Python
И последнее, что мы хотели бы показать вам, прежде чем двигаться дальше, это
Советы по эффективной веб-разработке с помощью Python
Советы по эффективной веб-разработке с помощью Python
Как веб-разработчик, Python может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
0
0
42
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Везде, куда вы вставляете медиа из статической папки, просто добавьте косую черту перед статической, чтобы браузер знал, что нужно идти вверх по пути URL.

Например: /static/logo.png /статические/style.css

Другие вопросы по теме