原发问者希望构建一个基于 Python 的 web 映射和数据可视化网站,但得知工作将在几个月后采用 Drupal。原发问者拥有丰富的 App Engine 网页开发经验,但缺乏 Drupal 经验,也担忧 Django 和 Drupal 之间的兼容性。同时,有关键的 Python 库和模块不能被替代或重写为 PHP。因此,原发问者正在寻找一种方法,在 Drupal 切换时,可以无缝地将 Python Web 应用集成到更大的 Drupal 网站中。
2. 解决方案
推荐的解决方案是使用 Python API 调用和 Drupal Services 模块。这样,原发问者可以将其他任何操作和发送/接收 JSON/XML 数据集成在一起。
from django.shortcuts import render
def index(request):
"""
Index view for the Django app.
Renders the index.html template with data from the API.
"""
context = {
'data': get_data_from_api()
}
return render(request, 'index.html', context)
def get_data_from_api():
"""
Fetches data from the API.
Returns a list of dictionaries with the data.
"""
url = 'http://example.com/api/data/'
response = requests.get(url)
data = response.json()
return data
上例中,index() 函数渲染index.html模板,并使用从 API 获取的数据填充模板中的变量。get_data_from_api() 函数负责从 API 获取数据,并以列表形式返回数据。
<?php
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Services\EndpointManager;
use Drupal\Services\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
class DataController {
/**
* The endpoint manager service.
*
* @var \Drupal\Services\EndpointManager
*/
protected $endpointManager;
/**
* The route match service.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $routeMatch;
/**
* Constructs a new DataController object.
*
* @param \Drupal\Services\EndpointManager $endpoint_manager
* The endpoint manager service.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match service.
*/
public function __construct(EndpointManager $endpoint_manager, RouteMatchInterface $route_match) {
$this->endpointManager = $endpoint_manager;
$this->routeMatch = $route_match;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('services.endpoint_manager'),
$container->get('current_route_match')
);
}
/**
* Responds to a data request.
*
* @return \Drupal\Services\ResourceResponse
* The resource response object.
*/
public function data() {
$endpoint_id = $this->routeMatch->getParameter('endpoint');
$endpoint = $this->endpointManager->getEndpoint($endpoint_id);
$data = $endpoint->get();
return new ResourceResponse($data);
}
}
上例中,DataController 类是一个 Drupal 控制器的示例,用于处理数据请求。该控制器使用EndpointManager 服务获取指定的端点,然后调用该端点来获取数据。最后,控制器使用ResourceResponse 类来将数据作为 JSON 响应返回。
通过使用 Python API 调用和 Drupal Services 模块,将 Python Web 应用集成到 Drupal 站点中变得更加简单。这样,原发问者可以专注于构建应用程序的功能,而无需担心与 Drupal 的兼容性问题。