### Install Blueapps Framework and Use bk-admin Source: https://context7.com/tencentblueking/blueapps/llms.txt This snippet shows how to install the blueapps-open package using pip and demonstrates the basic usage of the `bk-admin` command-line tool after installation. It's the initial step for setting up the framework. ```bash # Install blueapps framework pip install blueapps-open # After installation, you can use the bk-admin command bk-admin --help ``` -------------------------------- ### Mako Template Syntax Example Source: https://context7.com/tencentblueking/blueapps/llms.txt An example of a Mako template file showing inheritance, variable interpolation, loop iteration, and CSRF token inclusion. ```html <%inherit file="base.html"/> <%block name="content">

${title}

欢迎, ${user_info['nickname']}!

应用编码: ${APP_CODE}

${csrf_input}
``` -------------------------------- ### Enable XSS Protection Middleware in Blueapps Source: https://context7.com/tencentblueking/blueapps/llms.txt This snippet shows how to enable the XSS (Cross-Site Scripting) protection middleware in the Blueapps framework by adding `'blueapps.middleware.xss.middlewares.CheckXssMiddleware'` to the `MIDDLEWARE` setting in `settings.py`. This middleware automatically escapes GET and POST parameters. ```python # settings.py enable XSS protection middleware MIDDLEWARE = ( # ... other middleware 'blueapps.middleware.xss.middlewares.CheckXssMiddleware', ) ``` -------------------------------- ### Manage User Models and Properties in Blueapps Source: https://context7.com/tencentblueking/blueapps/llms.txt This snippet shows how to interact with the extended User model provided by Blueapps. It covers creating regular and super users, managing user properties (like department and phone number), setting and retrieving avatar URLs, and handling user display names. It also includes examples for sending and verifying two-factor authentication codes. ```python from blueapps.account.models import User, UserProperty # Create user user = User.objects.create_user( username='testuser', password='password123', nickname='Test User' ) # Create superuser admin = User.objects.create_superuser( username='admin', password='admin123', nickname='Administrator' ) # User property management user.set_property('department', 'R&D Department') user.set_property('phone', '13800138000') # Get user property department = user.get_property('department') print(department) # Output: R&D Department # Set and get avatar user.avatar_url = 'https://example.com/avatar.png' print(user.avatar_url) # Output: https://example.com/avatar.png # Get user display name print(user.get_full_name()) # Output: testuser(Test User) print(user.get_short_name()) # Output: Test User # Send verification code (two-factor authentication) result = user.send_code() # {'result': True, 'message': 'Initialization code, sent successfully'} # Verify user-entered verification code is_valid = user.verify_code('123456') if is_valid: print("Verification code is correct") else: print("Verification code is incorrect or expired") ``` -------------------------------- ### JavaScript Login and Redirection Logic Source: https://github.com/tencentblueking/blueapps/blob/master/blueapps/account/templates/account/login_page.html This JavaScript code handles the login process by making a GET request to validate the session and sets up a callback to close the login dialog and redirect the user. It relies on global variables `remote_static_url` and `refer_url`. ```javascript var remote_static_url = "{{ REMOTE_STATIC_URL }}"; var refer_url = "{{ refer_url }}"; $(function(){ login(); }) function login(){ // 仅触发弹框 $.get(refer_url, {"from_login_page": true}, function(){}, 'json'); window.close_login_dialog_after = function () { window.location.href = refer_url + window.location.hash; } } ``` -------------------------------- ### Use Login Exemption Decorator in Blueapps Source: https://context7.com/tencentblueking/blueapps/llms.txt This snippet demonstrates how to use the `login_exempt` decorator from `blueapps.account.decorators` to bypass login verification for specific views. It shows examples of exempting public APIs and health check endpoints, contrasting them with a default protected API that requires login. ```python from blueapps.account.decorators import login_exempt from django.http import JsonResponse @login_exempt def public_api(request): """ This interface does not require login to access """ return JsonResponse({ "code": 0, "data": {"message": "This is a public interface"}, "message": "success" }) @login_exempt def health_check(request): """ Health check interface for load balancer probing """ return JsonResponse({"status": "ok"}) # Interface requiring login (default behavior) def protected_api(request): """ This interface requires login to access Unauthenticated users will be redirected to the login page or return 401 """ return JsonResponse({ "code": 0, "data": {"user": request.user.username}, "message": "success" }) ``` -------------------------------- ### Call ESB APIs with Blueapps ESB Client Source: https://context7.com/tencentblueking/blueapps/llms.txt Demonstrates various methods to call Blueking ESB APIs using the blueapps ESB client. It covers calling via web request context, using an access token for backend calls, and obtaining a client by username. It also shows how to make custom API calls for endpoints not directly wrapped by the SDK. ```python # Method 1: Automatically get credentials from Web request context to call ESB API from blueapps.utils.esbclient import client # Call configuration platform interface to get user business list result = client.cc.get_app_by_user() print(result) # {'result': True, 'data': [...], 'message': 'success'} # Call job platform interface to execute script job_result = client.job.execute_job({ 'bk_biz_id': 2, 'job_plan_id': 1000001 }) # Method 2: Backend call via access_token from blueapps.utils.esbclient import backend_client b_client = backend_client(access_token="SfgcGlBHmPWttwlGd7nOLAbOP3TAOG") result = b_client.cc.get_app_by_user() # Method 3: Get client by username from blueapps.utils.esbclient import get_client_by_user client = get_client_by_user("admin") result = client.cmsi.send_mail({ 'receiver__username': 'user1', 'title': 'Notification Title', 'content': 'Notification Content' }) # Custom API call (for APIs that exist but are not wrapped by SDK) # Need to specify request method GET or POST result = client.cc.custom_api_name.get(param1="value1") result = client.cc.custom_api_name.post(data={"key": "value"}) ``` -------------------------------- ### Render Mako Templates in Views Source: https://context7.com/tencentblueking/blueapps/llms.txt Demonstrates how to pass a context dictionary to a Mako template using the standard Django render function. ```python from django.shortcuts import render def mako_page(request): context = { 'title': '页面标题', 'items': ['item1', 'item2', 'item3'], 'user_info': { 'name': request.user.username, 'nickname': request.user.nickname } } return render(request, 'home.html', context) ``` -------------------------------- ### Login Page with Redirect Source: https://context7.com/tencentblueking/blueapps/llms.txt Retrieves the login page with an option to specify a redirect URL after successful authentication. ```APIDOC ## GET /accounts/login_page/ ### Description This endpoint provides the login page. It accepts a `refer_url` query parameter to specify where the user should be redirected after a successful login. ### Method GET ### Endpoint `/accounts/login_page/` ### Query Parameters - **refer_url** (string) - Optional - The URL to redirect to after successful login. If not provided, a default redirect URL will be used. ``` -------------------------------- ### Configure User Authentication and Login in Blueapps Source: https://context7.com/tencentblueking/blueapps/llms.txt This snippet illustrates how to configure the user authentication system in Blueapps by defining authentication backends and middleware in `settings.py`. It supports multiple authentication methods like BK Token, JWT, and WeChat. It also shows how to retrieve user information in views. ```python # settings.py configure authentication backend AUTHENTICATION_BACKENDS = ( 'blueapps.account.backends.RioBackend', # Smart Gateway Authentication 'blueapps.account.backends.WeixinBackend', # WeChat Authentication 'blueapps.account.backends.UserBackend', # BK Token Authentication ) # Configure authentication middleware MIDDLEWARE = ( 'blueapps.middleware.request_provider.RequestProvider', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', # Login authentication middleware 'blueapps.account.middlewares.LoginRequiredMiddleware', 'blueapps.account.middlewares.WeixinLoginRequiredMiddleware', 'blueapps.account.middlewares.RioLoginRequiredMiddleware', ) # Use user model AUTH_USER_MODEL = 'account.User' # views.py get user information interface from django.http import JsonResponse import time def get_user_info(request): return JsonResponse({ "code": 0, "data": { "id": request.user.id, "username": request.user.username, "nickname": request.user.nickname, "avatar_url": request.user.avatar_url, "timestamp": time.time(), }, "message": "ok", }) ``` -------------------------------- ### 创建Celery任务 - Python Source: https://github.com/tencentblueking/blueapps/blob/master/docs/overview/project_usage.md 使用blueapps的bk-admin命令创建一个Celery任务。此代码定义了一个简单的加法任务,并指定了消息代理。需要安装celery库。 ```Python # cel.py from celery import Celery app = Celery('tasks', broker='pyamqp://admin@localhost//') @app.task def add(x, y): return x + y ``` -------------------------------- ### Configure Unified Login Authentication Backends for BlueApps Source: https://github.com/tencentblueking/blueapps/blob/master/blueapps/account/readme.md This snippet shows how to configure the authentication backends for unified login in BlueApps. It includes 'WeixinBackend' for WeChat authentication and 'UserBackend' for standard user authentication. These should be added to the Django AUTHENTICATION_BACKENDS setting. ```python AUTHENTICATION_BACKENDS = ( 'blueapps.account.backends.WeixinBackend', 'blueapps.account.backends.UserBackend', ) ``` -------------------------------- ### Configure Account URLs Source: https://context7.com/tencentblueking/blueapps/llms.txt Registers the built-in BlueApps account management routes, including login and user information endpoints, into the Django URL configuration. ```python from django.conf.urls import url, include urlpatterns = [ url(r'^accounts/', include('blueapps.account.urls')), ] ``` -------------------------------- ### Configure Mako Template Engine in Django Source: https://context7.com/tencentblueking/blueapps/llms.txt Configures the Mako template backend within the Django TEMPLATES setting. It defines the directory for Mako templates and specifies context processors for BlueKing integration. ```python MAKO_DIR_NAME = 'mako_templates' TEMPLATES = [ { 'BACKEND': 'blueapps.template.backends.mako.MakoTemplates', 'DIRS': (os.path.join(BASE_DIR, MAKO_DIR_NAME),), 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'blueapps.template.context_processors.blue_settings', ], 'module_directory': os.path.join( os.path.dirname(BASE_DIR), 'templates_module', APP_CODE ), }, }, ] ``` -------------------------------- ### XSS Decorators in Django Views Source: https://context7.com/tencentblueking/blueapps/llms.txt Demonstrates the use of BlueApps XSS decorators in Django views to prevent Cross-Site Scripting vulnerabilities. These decorators, such as `escape_exempt`, `escape_script`, `escape_url`, and `escape_exempt_param`, allow fine-grained control over HTML and script escaping of request parameters. ```python from blueapps.middleware.xss.decorators import ( escape_exempt, escape_script, escape_url, escape_exempt_param ) from django.http import JsonResponse @escape_exempt def raw_content_api(request): """ 完全豁免XSS转义,适用于富文本编辑器等场景 警告:需要自行处理XSS风险 """ content = request.POST.get('content', '') return JsonResponse({"content": content}) @escape_script def script_escape_api(request): """ 对参数进行JavaScript转义 防止XSS脚本注入 """ data = request.POST.get('data', '') return JsonResponse({"data": data}) @escape_url def url_escape_api(request): """ 对参数进行URL转义 适用于处理URL参数的场景 """ redirect_url = request.GET.get('redirect', '') return JsonResponse({"url": redirect_url}) @escape_exempt_param('content', 'raw_data') def partial_escape_api(request): """ 豁免特定参数的XSS转义 只有content和raw_data参数不会被转义 其他参数仍然会被HTML转义 """ content = request.POST.get('content', '') # 不转义 title = request.POST.get('title', '') # 会被转义 return JsonResponse({"content": content, "title": title}) ``` -------------------------------- ### 启动Celery Worker - Shell Source: https://github.com/tencentblueking/blueapps/blob/master/docs/overview/project_usage.md 使用bk-admin命令启动Celery worker来执行任务。此命令需要指定包含任务定义的模块。确保Celery已正确配置。 ```Shell bk-admin celery -A cel worker --loglevel=INFO ``` -------------------------------- ### Add Unified Login Middleware to BlueApps Source: https://github.com/tencentblueking/blueapps/blob/master/blueapps/account/readme.md This snippet demonstrates how to add the necessary middleware for unified login authentication in BlueApps. It includes 'WeixinLoginRequiredMiddleware' for WeChat login and 'LoginRequiredMiddleware' for general login requirements. These should be added to the Django MIDDLEWARE setting. ```python MIDDLEWARE = ( # Auth middleware 'blueapps.account.middlewares.WeixinLoginRequiredMiddleware', 'blueapps.account.middlewares.LoginRequiredMiddleware', ) ``` -------------------------------- ### Unified Exception Handling in Django Source: https://context7.com/tencentblueking/blueapps/llms.txt Implements centralized exception handling in Django applications using BlueApps' custom exception classes. This system ensures consistent error response formats across the application, simplifying error management and debugging. It covers various exception types like `ParamRequired`, `ResourceNotFound`, and `AccessForbidden`. ```python from blueapps.core.exceptions import ( BlueException, ClientBlueException, ServerBlueException, ResourceNotFound, ParamValidationError, ParamRequired, AccessForbidden, RequestForbidden, MethodError, DatabaseError, ApiNetworkError, ApiResultError ) from django.http import JsonResponse def my_api(request): user_id = request.GET.get('user_id') # 参数缺失异常 if not user_id: raise ParamRequired(message="user_id参数必填") # 参数验证异常 if not user_id.isdigit(): raise ParamValidationError(message="user_id必须为数字") # 资源不存在异常 user = User.objects.filter(id=user_id).first() if not user: raise ResourceNotFound(message="用户不存在") # 权限拒绝异常 if not request.user.has_perm('view_user'): raise AccessForbidden(message="无权查看用户信息") return JsonResponse({ "result": True, "data": {"username": user.username}, "message": "success" }) # 自定义业务异常 class BusinessException(ClientBlueException): ERROR_CODE = "40010" MESSAGE = "业务处理失败" STATUS_CODE = 400 def business_api(request): try: # 业务逻辑 process_business() except Exception as e: raise BusinessException(message=str(e), data={"detail": "处理订单失败"}) # 异常响应格式示例 # { # "result": False, # "code": "40010", # "message": "业务处理失败", # "data": {"detail": "处理订单失败"} # } ``` -------------------------------- ### Declare User Model for BlueApps Account Source: https://github.com/tencentblueking/blueapps/blob/master/blueapps/account/readme.md This snippet shows how to declare the AUTH_USER_MODEL setting to use the 'account.User' model provided by the blueapps.account module. This is essential for the framework to correctly manage user authentication and data. ```python AUTH_USER_MODEL = 'account.User' ``` -------------------------------- ### Close Login Dialog and Post Message (JavaScript) Source: https://github.com/tencentblueking/blueapps/blob/master/blueapps/account/templates/account/login_success.html This JavaScript code checks if an opener window exists. If so, it sends a 'login' message to the opener. Otherwise, it attempts to close the login dialog using Blueking's core functions or parent window methods. ```javascript if (window.opener) { $(document).ready(function () { // 关闭登录弹出框 window.opener.postMessage("login", '*'); }); } else { $(document).ready(function () { // 关闭登录弹出框 try { window.top.BLUEKING.corefunc.close_login_dialog(); } catch (err) { try { window.parent.close_login_dialog(); } catch (err) {} } }); } ``` -------------------------------- ### Access Request Object via RequestProvider Source: https://context7.com/tencentblueking/blueapps/llms.txt Utilizes the RequestProvider middleware to access the current request object in non-view contexts, such as utility functions or ESB API clients. ```python from blueapps.utils.request_provider import get_request, get_x_request_id from blueapps.utils.esbclient import client def utility_function(): request = get_request() return { "username": request.user.username, "x_request_id": get_x_request_id() } def call_esb_api(): # Automatically uses current request context return client.cc.get_app_by_user() ``` -------------------------------- ### Celery Asynchronous Tasks in Django Source: https://context7.com/tencentblueking/blueapps/llms.txt Integrates Celery for background task processing within a Django application. This snippet shows how to define asynchronous tasks, such as sending emails and processing data with retries, and how to trigger these tasks from Django views. It also includes commands for managing Celery workers and beat. ```python # config/celery.py 或使用框架内置配置 from blueapps.core.celery import celery # 框架已自动配置Celery实例 # from celery import Celery, platforms # platforms.C_FORCE_ROOT = True # app = Celery("proj") # app.config_from_object("django.conf:settings") # app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) # tasks.py 定义异步任务 from celery import shared_task @shared_task def send_email_task(to_email, subject, content): """ 发送邮件的异步任务 """ from blueapps.utils.esbclient import client result = client.cmsi.send_mail({ 'receiver__username': to_email, 'title': subject, 'content': content }) return result @shared_task(bind=True, max_retries=3) def process_data_task(self, data_id): """ 带重试机制的数据处理任务 """ try: # 处理数据逻辑 process_data(data_id) return {"status": "success", "data_id": data_id} except Exception as exc: # 失败后重试,指数退避 raise self.retry(exc=exc, countdown=60 * (2 ** self.request.retries)) # views.py 调用异步任务 def trigger_email(request): # 异步发送邮件 task = send_email_task.delay( to_email='user@example.com', subject='测试邮件', content='这是一封测试邮件' ) return JsonResponse({ "result": True, "data": {"task_id": task.id}, "message": "邮件任务已提交" }) ``` ```bash # 启动Celery Worker bk-admin celery -A config worker --loglevel=INFO # 启动Celery Beat(定时任务调度器) bk-admin celery -A config beat --loglevel=INFO # 从djcelery迁移数据 bk-admin migrate_from_djcelery ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.