Introducción
La migración de un project a un nuevo lenguaje de programación puede ser una tarea difícil y lenta. GitHub Copilot puede ayudarle con este proceso explicando los cambios que necesita para realizar y sugerir código de reemplazo en el nuevo lenguaje.
Principios de migración de un project a un nuevo idioma
Ten en cuenta los puntos antes de iniciar un proceso de migración:
-
Conocimientos de codificación
Asegúrate de tener una buena comprensión de ambos lenguajes de programación. Aunque Copilot puede traducir código automáticamente, debe comprender las opciones que propone y decidir si desea usar sus sugerencias o solicitar una sugerencia alternativa.
-
Conocimientos del sistema que vas a migrar
Asegúrate de comprender la arquitectura y la lógica del sistema actual, además de las funciones y características que proporciona a los usuarios. Debes poder comprobar que el código traducido realiza todas las mismas operaciones que el código original y genera los mismos resultados.
-
Uso de la inteligencia artificial para ayudarte
Si no entiendes alguna parte concreta del código que vas a traducir, usa la función «explicar» de Copilot, ya sea en todo el archivo o en una parte seleccionada del código de un archivo. Consulte Hacer preguntas a GitHub Copilot en un IDE.
-
Programar la hora de finalización de la migración
La conversión es un proceso de varias fases. Cuanto mayor sea el proyecto que va a convertir, mayor será el número de pasos que tendrá que realizar. Asegúrate de tener el suficiente tiempo para completar todo el proceso.
-
Trabajar iterativamente
Procure convertir partes discretas de su proyecto por separado. Asegúrese de haber comprobado todos los cambios realizados antes de pasar a otra parte del project. Escriba pruebas para las partes individuales del project a medida que continúe para que pueda confirmar que cada uno de los nuevos componentes funciona según lo previsto.
-
Evitar la introducción de complejidad en el proceso
Inicialmente, debe intentar realizar una conversión similar. Esto no será posible para todo el código de tu proyecto. Sin embargo, para evitar agregar complejidad a la tarea de migración, debes intentar limitar el número de cambios nuevos que se introducen, aparte de traducir el código y usar un nuevo marco y las dependencias adecuadas.
-
Prueba comparativa y refactorización del código traducido
Una vez que hayas completado la conversión inicial y tengas un sistema funcional, puedes realizar pruebas comparativas para comparar los sistemas antiguos y nuevos. Ahora puedes refactorizar el código en el nuevo lenguaje. Esta es una oportunidad para optimizar el código y reducir la deuda técnica.
Uso Copilot para ayudarle a migrar un proyecto a un nuevo lenguaje
Suponiendo que ya te has familiarizado con el proyecto existente, una buena manera de empezar una migración es abrir una rama del repositorio en tu editor y pedir ayuda a Copilot.
-
En el editor, abra el Chat de Copiloto panel. Consulte Hacer preguntas a GitHub Copilot en un IDE.
-
Pida Copilot que describa los pasos que debe seguir para migrar el proyecto al nuevo lenguaje.
Por ejemplo, para una migración de PHP a Python, podrías preguntar:
Copilot prompt @workspace I want to migrate this project from PHP to Python. Give me a high-level overview of the steps I need to take. Don't go into detail at this stage.
@workspace I want to migrate this project from PHP to Python. Give me a high-level overview of the steps I need to take. Don't go into detail at this stage.Nota:
El participante del chat
@workspaceestablece los archivos en el área de trabajo actual como contexto de la pregunta que se formula.
Copilot normalmente volverá con una lista de los pasos que debe realizar para migrar el proyecto.
-
Copia la respuesta de Copilot y guárdala en algún sitio para consultarla durante todo el proceso.
-
Avance por cada paso del proceso, pidiendo ayuda detallada de Copilot cuando la necesite.
Tenga en cuenta cada sugerencia Copilot con atención. Asegúrese de comprender el código que sugiere y evalúe si es adecuado para su project. Si no está seguro, pida que Copilot explique el código.
Si cree que un cambio sugerido por Copilot no es correcto de alguna manera, solicite una sugerencia alternativa.
-
En cuanto hayas migrado un componente a un estado que puedas ejecutar, comprueba que funciona según lo previsto. Si se genera un error, copia el error en la vista Chat de Copiloto y pídele a Copilot que te ayude a corregirlo.
-
Una vez completada la conversión inicial, use Copilot para ayudarle a refactorizar el código en el nuevo lenguaje. Para obtener más información, vea Refactorización de código con GitHub Copilot.
Ejemplo: migración de un project PHP a Python
En el ejemplo siguiente se describe la migración de una aplicación web sencilla de PHP a Python. Incluso si estos no son los lenguajes de programación que está utilizando para su migración, puede resultarle útil seguir los pasos descritos aquí para familiarizarse con la migración de un proyecto. Los pasos serán similares para migrar otros proyectos pequeños de un lenguaje a otro.

En este ejemplo se da por supuesto que:
- Está trabajando en Visual Studio Code.
- Tienes instalados ambos lenguajes: PHP y Python versión 3.12 o posterior.
Migración de un proyecto de sitio web sencillo
Vamos a migrar el código de este repositorio público en GitHub: docs/simple-php-website.
El repositorio consta de los siguientes archivos.
.gitignore
.htaccess
LICENSE
content
├── 404.phtml
├── about-us.phtml
├── contact.phtml
├── home.phtml
└── products.phtml
includes
├── config.php
└── functions.php
index.php
readme.md
template
├── style.css
└── template.php
Este ejemplo muestra las solicitudes que puede introducir en Chat de Copiloto para completar la migración, y las respuestas que Copilot devolvió para un caso de esta migración. El GPT-4.1 modelo se usó para generar estas respuestas. Chat de Copiloto las respuestas son no deterministas, por lo que probablemente obtendrá respuestas ligeramente diferentes a las que se muestran aquí.
Durante un proceso de migración, es probable que obtengas errores que debes corregir antes de continuar. Copilot puede ayudarle con esto. El ejemplo incluye algunos errores y muestra cómo puede hacer que Copilot le ayude a corregirlos.
Dado que es probable que las respuestas que obtenga Chat de Copiloto sean diferentes de las que se muestran aquí, es posible que encuentre errores diferentes. Por lo tanto, puede que le resulte más fácil seguir este ejemplo de migración paso a paso usando las respuestas que se muestran aquí, en lugar de las que obtenga usted mismo de Copilot.
Después de completar esta migración de ejemplo, puede usar la misma metodología en su propio proyecto.
-
Empieza por clonar una copia del repositorio en el equipo local.
-
Ejecuta la aplicación para comprobar que funciona.
Para hacer esto, en una terminal, navegue a la raíz del repositorio clonado y ejecute el siguiente comando:
Shell php -S localhost:8000
php -S localhost:8000A continuación, en un explorador, ve a: http://localhost:8000.
-
Haz clic por el sitio web para familiarizarte con él, de modo que puedas verificar que la migración se ha realizado correctamente.
-
Cree una rama de trabajo en su repositorio y ábrala como un nuevo espacio de trabajo en Visual Studio Code.
-
Familiarícese con el contenido y la arquitectura del proyecto existente. Copilot puede ayudarle con esto:
-
Abra la vista Chat de Copiloto.
-
Escribe una indicación como:
Copilot prompt @workspace Describe this project in detail, explaining what the various components do and how they interact.
@workspace Describe this project in detail, explaining what the various components do and how they interact.
-
-
Solicite Copilot información general de alto nivel sobre el proceso de migración:
Copilot prompt @workspace I want to migrate this project from PHP to Python. Give me a high-level overview of the steps I need to take. Don't go into detail at this stage.
@workspace I want to migrate this project from PHP to Python. Give me a high-level overview of the steps I need to take. Don't go into detail at this stage.
Copilot responderá con instrucciones como:
To migrate this project from PHP to Python, follow these high-level steps:
1. Set Up Python Environment:
- Install Python and set up a virtual environment.
- Install necessary packages (e.g., Flask for web framework).
2. Convert Configuration:
- Translate the configuration settings from config.php to a Python configuration file.
3. Rewrite Functions:
- Convert PHP functions in functions.php to Python functions.
4. Create Flask Application:
- Set up a Flask application to handle routing and views.
- Map the routes to corresponding views.
5. Convert Templates:
- Translate template.php to a Jinja2 template.
- Update the CSS file path in the template.
6. Convert Content Pages:
- Convert .phtml content files to HTML or Jinja2 templates.
7. Update .htaccess Rules:
- Translate .htaccess rewrite rules to Flask route handling.
8. Run and Test:
- Run the Flask application and test all routes and functionalities.
- Ensure the site works as expected and fix any issues.
9. Documentation:
- Update the readme.md with new instructions for running the Python project.
-
Copie la respuesta de Copilot y guárdela en algún sitio para poder consultarla durante el resto de este proceso. Seguirás cada uno de estos pasos, pidiendo ayuda a Copilot a medida que avanzas.
-
Si aún no ha decidido qué marco Python quiere usar, puede pedir Copilot consejos:
Copilot prompt @workspace What Python frameworks can I use for this project once it is migrated to Python? Give me a selection of options, with a brief summary of the pros and cons of each in relation to this website project. Which framework would you recommend?
@workspace What Python frameworks can I use for this project once it is migrated to Python? Give me a selection of options, with a brief summary of the pros and cons of each in relation to this website project. Which framework would you recommend?
Copilot responde con información sobre varios marcos y concluye:
For a project like yours - which is a simple, content-driven website - Flask is highly recommended. Its simplicity, flexibility, and ease of use (especially with its templating system that can easily replace your current PHP template structure) make it a great fit.
Seguiremos el consejo de Copilot y usaremos Flask.
-
Volviendo a Copilot la descripción general, el primer paso es configurar un entorno de Python e instalar los paquetes necesarios. Para averiguar cómo hacerlo, en Chat de Copiloto, escriba:
Copilot prompt @workspace I want to use Flask. Tell me how to set up a virtual environment and install the necessary packages.
@workspace I want to use Flask. Tell me how to set up a virtual environment and install the necessary packages.
Copilot responderá con instrucciones como:
1. Create a virtual environment:
- Open a terminal and navigate to your project directory.
- Run the following command to create a virtual environment:
python3 -m venv venv
2. Activate the virtual environment:
- On macOS and Linux:
source venv/bin/activate
- On Windows:
venv\Scripts\activate
3. Install Flask and necessary packages:
- With the virtual environment activated, run the following command
to install Flask and other necessary packages:
pip install Flask
4. Verify the installation:
- You can verify that Flask is installed by running:
pip list
-
Siga Copilotlas instrucciones y use
pip listpara comprobar que Flask está instalado. -
Volviendo a la descripción general de Copilot sobre el proceso de migración, el siguiente paso es convertir la configuración. Pida ayuda a Copilot con esto. Por ejemplo:
Copilot prompt @workspace As the first step in migrating this project from PHP to Python, create a Python configuration file by converting the functions in functions.php to Python functions. Tell me where to locate the Python config file in the project.
@workspace As the first step in migrating this project from PHP to Python, create a Python configuration file by converting the functions in functions.php to Python functions. Tell me where to locate the Python config file in the project.
Copilot sugiere que se crea un archivo llamado config.py en el includes directorio , que contiene el código siguiente.
config = {
'name': 'Simple Python Website',
'site_url': '',
'pretty_uri': False,
'nav_menu': {
'': 'Home',
'about-us': 'About Us',
'products': 'Products',
'contact': 'Contact',
},
'template_path': 'template',
'content_path': 'content',
'version': 'v3.1',
}
def get_config(key=''):
return config.get(key, None)
def site_name():
return get_config('name')
def site_url():
return get_config('site_url')
def site_version():
return get_config('version')
def nav_menu(sep=' | '):
nav_menu = ''
nav_items = get_config('nav_menu')
for uri, name in nav_items.items():
query_string = request.args.get('page', '')
class_active = ' active' if query_string == uri else ''
url = f"{get_config('site_url')}/{'' if get_config('pretty_uri') or uri == '' else '?page='}{uri}"
nav_menu += f'<a href="{url}" title="{name}" class="item{class_active}">{name}</a>{sep}'
return nav_menu.strip(sep)
def page_title():
page = request.args.get('page', 'Home')
return ' '.join(word.capitalize() for word in page.split('-'))
def page_content():
page = request.args.get('page', 'home')
path = os.path.join(os.getcwd(), get_config('content_path'), f'{page}.phtml')
if not os.path.exists(path):
path = os.path.join(os.getcwd(), get_config('content_path'), '404.phtml')
with open(path, 'r') as file:
return file.read()
def init():
template_path = os.path.join(get_config('template_path'), 'template.html')
with open(template_path, 'r') as file:
return file.read()
config = {
'name': 'Simple Python Website',
'site_url': '',
'pretty_uri': False,
'nav_menu': {
'': 'Home',
'about-us': 'About Us',
'products': 'Products',
'contact': 'Contact',
},
'template_path': 'template',
'content_path': 'content',
'version': 'v3.1',
}
def get_config(key=''):
return config.get(key, None)
def site_name():
return get_config('name')
def site_url():
return get_config('site_url')
def site_version():
return get_config('version')
def nav_menu(sep=' | '):
nav_menu = ''
nav_items = get_config('nav_menu')
for uri, name in nav_items.items():
query_string = request.args.get('page', '')
class_active = ' active' if query_string == uri else ''
url = f"{get_config('site_url')}/{'' if get_config('pretty_uri') or uri == '' else '?page='}{uri}"
nav_menu += f'<a href="{url}" title="{name}" class="item{class_active}">{name}</a>{sep}'
return nav_menu.strip(sep)
def page_title():
page = request.args.get('page', 'Home')
return ' '.join(word.capitalize() for word in page.split('-'))
def page_content():
page = request.args.get('page', 'home')
path = os.path.join(os.getcwd(), get_config('content_path'), f'{page}.phtml')
if not os.path.exists(path):
path = os.path.join(os.getcwd(), get_config('content_path'), '404.phtml')
with open(path, 'r') as file:
return file.read()
def init():
template_path = os.path.join(get_config('template_path'), 'template.html')
with open(template_path, 'r') as file:
return file.read()
-
Cree el archivo
includes/config.pyy elimina el archivoincludes/config.phpexistente. -
Al volver al resumen general, pida a Copilot que le ayude a reescribir las funciones de PHP.
Copilot prompt @workspace Continuing the migration of this project from PHP to Python, create Python functions to replace the existing PHP functions. Tell me where to locate the Python functions in the project.
@workspace Continuing the migration of this project from PHP to Python, create Python functions to replace the existing PHP functions. Tell me where to locate the Python functions in the project.
Copilot sugiere crear un archivo llamado functions.py en el includes directorio , que contiene el código siguiente.
import os
from flask import request
from .config import get_config
def site_name():
return get_config('name')
def site_url():
return get_config('site_url')
def site_version():
return get_config('version')
def nav_menu(sep=' | '):
nav_menu = ''
nav_items = get_config('nav_menu')
for uri, name in nav_items.items():
query_string = request.args.get('page', '')
class_active = ' active' if query_string == uri else ''
url = f"{get_config('site_url')}/{'' if get_config('pretty_uri') or uri == '' else '?page='}{uri}"
nav_menu += f'<a href="{url}" title="{name}" class="item{class_active}">{name}</a>{sep}'
return nav_menu.strip(sep)
def page_title():
page = request.args.get('page', 'Home')
return ' '.join(word.capitalize() for word in page.split('-'))
def page_content():
page = request.args.get('page', 'home')
path = os.path.join(os.getcwd(), get_config('content_path'), f'{page}.phtml')
if not os.path.exists(path):
path = os.path.join(os.getcwd(), get_config('content_path'), '404.phtml')
with open(path, 'r') as file:
return file.read()
def init():
template_path = os.path.join(get_config('template_path'), 'template.html')
with open(template_path, 'r') as file:
return file.read()
import os
from flask import request
from .config import get_config
def site_name():
return get_config('name')
def site_url():
return get_config('site_url')
def site_version():
return get_config('version')
def nav_menu(sep=' | '):
nav_menu = ''
nav_items = get_config('nav_menu')
for uri, name in nav_items.items():
query_string = request.args.get('page', '')
class_active = ' active' if query_string == uri else ''
url = f"{get_config('site_url')}/{'' if get_config('pretty_uri') or uri == '' else '?page='}{uri}"
nav_menu += f'<a href="{url}" title="{name}" class="item{class_active}">{name}</a>{sep}'
return nav_menu.strip(sep)
def page_title():
page = request.args.get('page', 'Home')
return ' '.join(word.capitalize() for word in page.split('-'))
def page_content():
page = request.args.get('page', 'home')
path = os.path.join(os.getcwd(), get_config('content_path'), f'{page}.phtml')
if not os.path.exists(path):
path = os.path.join(os.getcwd(), get_config('content_path'), '404.phtml')
with open(path, 'r') as file:
return file.read()
def init():
template_path = os.path.join(get_config('template_path'), 'template.html')
with open(template_path, 'r') as file:
return file.read()
-
Cree el archivo
includes/functions.pyy elimina el archivoincludes/functions.phpexistente. -
Siguiendo con la información general, el siguiente paso es crear una aplicación de Flask. Pídale Copilot que le ayude con esto:
Copilot prompt @workspace Set up a Flask application to handle routing and views, and map the routes to corresponding views. Tell me the location of any files that need to be created or changed.
@workspace Set up a Flask application to handle routing and views, and map the routes to corresponding views. Tell me the location of any files that need to be created or changed.
Copilot sugiere crear un archivo llamado app.py en la raíz del proyecto, que contiene el código siguiente.
from flask import Flask, render_template, request
import os
app = Flask(__name__)
config = {
'name': 'Simple Python Website',
'site_url': '',
'pretty_uri': False,
'nav_menu': {
'': 'Home',
'about-us': 'About Us',
'products': 'Products',
'contact': 'Contact',
},
'template_path': 'template',
'content_path': 'content',
'version': 'v3.1',
}
def get_config(key=''):
return config.get(key, None)
@app.route('/')
@app.route('/<page>')
def index(page='home'):
page_content = get_page_content(page)
page_title = get_page_title(page)
nav_menu = get_nav_menu()
return render_template('template.html', page_title=page_title, page_content=page_content, nav_menu=nav_menu)
def get_page_title(page):
return ' '.join(word.capitalize() for word in page.split('-'))
def get_page_content(page):
path = os.path.join(os.getcwd(), get_config('content_path'), f'{page}.phtml')
if not os.path.exists(path):
path = os.path.join(os.getcwd(), get_config('content_path'), '404.phtml')
with open(path, 'r') as file:
return file.read()
def get_nav_menu(sep=' | '):
nav_menu = ''
nav_items = get_config('nav_menu')
for uri, name in nav_items.items():
query_string = request.args.get('page', '')
class_active = ' active' if query_string == uri else ''
url = f"{get_config('site_url')}/{'' if get_config('pretty_uri') or uri == '' else '?page='}{uri}"
nav_menu += f'<a href="{url}" title="{name}" class="item{class_active}">{name}</a>{sep}'
return nav_menu.strip(sep)
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask, render_template, request
import os
app = Flask(__name__)
config = {
'name': 'Simple Python Website',
'site_url': '',
'pretty_uri': False,
'nav_menu': {
'': 'Home',
'about-us': 'About Us',
'products': 'Products',
'contact': 'Contact',
},
'template_path': 'template',
'content_path': 'content',
'version': 'v3.1',
}
def get_config(key=''):
return config.get(key, None)
@app.route('/')
@app.route('/<page>')
def index(page='home'):
page_content = get_page_content(page)
page_title = get_page_title(page)
nav_menu = get_nav_menu()
return render_template('template.html', page_title=page_title, page_content=page_content, nav_menu=nav_menu)
def get_page_title(page):
return ' '.join(word.capitalize() for word in page.split('-'))
def get_page_content(page):
path = os.path.join(os.getcwd(), get_config('content_path'), f'{page}.phtml')
if not os.path.exists(path):
path = os.path.join(os.getcwd(), get_config('content_path'), '404.phtml')
with open(path, 'r') as file:
return file.read()
def get_nav_menu(sep=' | '):
nav_menu = ''
nav_items = get_config('nav_menu')
for uri, name in nav_items.items():
query_string = request.args.get('page', '')
class_active = ' active' if query_string == uri else ''
url = f"{get_config('site_url')}/{'' if get_config('pretty_uri') or uri == '' else '?page='}{uri}"
nav_menu += f'<a href="{url}" title="{name}" class="item{class_active}">{name}</a>{sep}'
return nav_menu.strip(sep)
if __name__ == '__main__':
app.run(debug=True)
Copilot también sugiere cambiar el nombre de template/template.php a template/template.html y actualizar el archivo para que use la sintaxis de plantillas de Jinja2:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
<title>{{ page_title }} | {{ get_config('name') }}</title>
<link href="{{ get_config('site_url') }}/template/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="wrap">
<header>
<h1>{{ get_config('name') }}</h1>
<nav class="menu">
{{ nav_menu|safe }}
</nav>
</header>
<article>
<h2>{{ page_title }}</h2>
{{ page_content|safe }}
</article>
<footer>
<small>©{{ get_config('version') }} {{ get_config('name') }}.<br>{{ get_config('version') }}</small>
</footer>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
<title>{{ page_title }} | {{ get_config('name') }}</title>
<link href="{{ get_config('site_url') }}/template/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="wrap">
<header>
<h1>{{ get_config('name') }}</h1>
<nav class="menu">
{{ nav_menu|safe }}
</nav>
</header>
<article>
<h2>{{ page_title }}</h2>
{{ page_content|safe }}
</article>
<footer>
<small>©{{ get_config('version') }} {{ get_config('name') }}.<br>{{ get_config('version') }}</small>
</footer>
</div>
</body>
</html>
-
Crea los archivos
app.pyytemplate/template.htmlcomo se sugiere. -
Copilot también puede sugerir que, después de crear estos archivos, ejecutes ahora
python app.pyen el terminal, desde la raíz del repositorio, y luego vayas a http://127.0.0.1:5000.Nota:
En función de cómo esté instalado Python en el equipo, es posible que tengas que usar el comando
python3 app.pyen lugar depython app.pypara asegurarte de que se usa la versión correcta de Python.Al hacerlo, verás mensajes de error en el explorador.
-
Copie el mensaje de error inicial
TemplateNotFounden la Chat de Copiloto vista y pregunte cómo puede corregirlo. Por ejemplo:Copilot prompt @workspace When I run `python3 app.py`, I get the following error in the browser: `jinja2.exceptions.TemplateNotFound: template.html`. How can I fix this?
@workspace When I run `python3 app.py`, I get the following error in the browser: `jinja2.exceptions.TemplateNotFound: template.html`. How can I fix this?
Copilot responde que el error indica que Flask no puede encontrar el template.html archivo.
Indica que, de forma predeterminada, Flask busca plantillas en una carpeta denominada templates en el directorio raíz de la project. Sin embargo, el archivo template.html se encuentra en el directorio template. Para corregirlo, debes especificar la carpeta de plantilla correcta al crear la aplicación Flask. Te aconseja actualizar el archivo app.py y cambiar la asignación app = Flask(__name__) para incluir el parámetro template_folder:
app = Flask(__name__, template_folder='template')
app = Flask(__name__, template_folder='template')
-
Suponiendo que el servidor de desarrollo de Flask todavía se esté ejecutando, si actualizas la página del explorador en http://127.0.0.1:5000/, ahora verás un nuevo error relacionado con la función
get_config.Copie este mensaje de error en la Chat de Copiloto vista y solicite ayuda.
Copilot prompt @workspace When I run `python3 app.py`, I get the following error in the browser: `jinja2.exceptions.UndefinedError: 'get_config' is undefined.` How can I fix this?
@workspace When I run `python3 app.py`, I get the following error in the browser: `jinja2.exceptions.UndefinedError: 'get_config' is undefined.` How can I fix this?
Copilot responde que se produce el error porque get_config no está disponible en el contexto de plantilla de Jinja2. Te aconseja agregar el código siguiente al archivo app.py, directamente antes de la línea @app.route('/'):
app.jinja_env.globals.update(get_config=get_config)
app.jinja_env.globals.update(get_config=get_config)
-
Actualiza el explorador y ahora deberías ver el sitio web.

Sin embargo, no se aplica ninguno de los estilos CSS. Lo corregiremos a continuación.
-
Pregunta Copilot:
Copilot prompt @workspace The deployed website does not use the CSS styles. How can I fix this?
@workspace The deployed website does not use the CSS styles. How can I fix this?
Copilot indica que Flask espera que el archivo CSS esté en un directorio denominado static. Sugiere mover el archivo style.css existente del directorio template a un nuevo directorio static y, a continuación, actualizar la ruta de acceso al archivo style.css dentro de la parte head del archivo template.html. Cambia esto a:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
Al actualizar el explorador, el sitio web ahora debería representarse correctamente.
Para completar la migración inicial, siga trabajando en los pasos descritos en la información general de alto nivel que Copilot le proporcionó, solicitando ayuda cuando lo necesite.
Finalización de la migración
El trabajo adicional para completar correctamente el proceso de migración implicaría lo siguiente:
- Comprobación exhaustiva de la migración inicial.
- Corrección de errores. Por ejemplo, en la actualidad en el ejemplo descrito aquí, los vínculos de página solo funcionan si estableces
pretty_urienTrueen la secciónconfigdel archivoapp.py. Si desea poder usar parámetros de cadena de consulta en las URL de la página, o si desea eliminar esta opción del código, puede pedirle ayuda a Copilot para hacerlo. - Escribiendo pruebas para el proyecto migrado.
- Limpie el proyecto quitando los archivos que ya no sean necesarios.
- Refactoriza el código en el nuevo lenguaje. El proceso de migración ha dado lugar a una project de Python cuya arquitectura se basa en la del project PHP original. Después de realizar la migración inicial, ahora puedes refactorizar el código para aprovechar mejor las características del lenguaje Python y el marco de Flask.
- Actualización de la documentación. El archivo
readme.mdya no está actualizado y debe volver a escribirse.