小编Han*_*nny的帖子

修补程序请求未修补 - 返回 403 - django Rest Framework

我正在尝试使用补丁请求测试 API 端点以确保其正常工作。

我正在使用APILiveServerTestCase,但似乎无法获得修补该项目所需的权限。我创建了一个用户 ( adminuser),他是超级管理员,可以访问所有内容和所有权限。

我的测试用例如下所示:

class FutureVehicleURLTest(APILiveServerTestCase):
    def setUp(self):
        # Setup users and some vehicle data we can query against
        management.call_command("create_users_and_vehicle_data", verbosity=0)
        self.user = UserFactory()
        self.admin_user = User.objects.get(username="adminuser")
        self.future_vehicle = f.FutureVehicleFactory(
            user=self.user,
            last_updated_by=self.user,
        )
        self.vehicle = f.VehicleFactory(
            user=self.user,
            created_by=self.user,
            modified_by=self.user,
        )
        self.url = reverse("FutureVehicles-list")
        self.full_url = self.live_server_url + self.url
        time = str(datetime.now())
        self.form_data = {
            "signature": "TT",
            "purchasing": True,
            "confirmed_at": time,
        }
Run Code Online (Sandbox Code Playgroud)

我已经尝试了多种不同的方法进行此测试 - 所有方法都给出相同的结果(403)。

我已经在测试中设置了 python 调试器,并且我已经尝试实际进入http://localhost:xxxxx/admin/浏览器并使用任何用户手动登录,但是当我单击登录时页面只会刷新,并且我从未“登录”以查看管理员。我不确定这是否是因为它不能在这样的调试器中完全工作。

我的测试如下所示(使用 Requests 库):

    def test_patch_request_updates_object(self): …
Run Code Online (Sandbox Code Playgroud)

python django django-testing django-rest-framework

10
推荐指数
1
解决办法
1306
查看次数

为什么模拟补丁仅在运行特定测试而不是整个测试套件时起作用?

我专门使用 Django 和 Pytest 来运行测试套件,并尝试测试当用户访问网站时特定表单是否显示预期数据(集成测试)。

这个特定的视图使用一个存储过程,我正在嘲笑它,因为测试永远无法访问它。

我的测试代码如下所示:

#test_integrations.py

from my_app.tests.data_setup import setup_data, setup_sb7_data
from unittest.mock import patch

...

# Setup to use a non-headless browser so we can see whats happening for debugging
@pytest.mark.usefixtures("standard_browser")
class SeniorPageTestCase(StaticLiveServerTestCase):
    """
    These tests surround the senior form
    """

    @classmethod
    def setUpClass(cls):
        cls.host = socket.gethostbyname(socket.gethostname())
        super(SeniorPageTestCase, cls).setUpClass()

    def setUp(self):
        # setup the dummy data - this works fine
        basic_setup(self)
        # setup the 'results'
        self.sb7_mock_data = setup_sb7_data(self)

    @patch("my_app.utils.get_employee_sb7_data")
    def test_senior_form_displays(self, mock_sb7_get):
        # login the dummy user …
Run Code Online (Sandbox Code Playgroud)

django unit-testing mocking pytest liveservertestcase

9
推荐指数
1
解决办法
3846
查看次数

在 Django 中传递消息时重定向

在检查user_settings用户是否存在(如果它们不存在 - 用户被带到表单输入并保存它们)后,我试图运行重定向。

我想将用户重定向到适当的表单,并告诉他们必须“保存他们的设置”,以便他们知道为什么要重定向。

该函数如下所示:

def trip_email(request):
    try:
        user_settings = Settings.objects.get(user_id=request.user.id)
    except Exception as e:
        messages.error(request, 'Please save your settings before you print mileage!')
        return redirect('user_settings')
Run Code Online (Sandbox Code Playgroud)

此功能检查用户设置并适当地重定向我 - 但该消息从未出现在模板的顶部。

您可能首先会想:“您的 Django 中的消息设置是否正确?”

我还有其他功能,我使用重定向消息,消息在模板中按预期显示,没有问题。消息被适当地集成到我的模板中并起作用。

只有当我使用时redirect,我才看到我正在发送的消息。

如果我render像下面这样使用,我会看到消息(但当然,URL 不会改变 - 我希望发生这种情况)。

def trip_email(request):
    try:
        user_settings = Settings.objects.get(user_id=request.user.id)
    except Exception as e:
        messages.error(request, 'Please save your settings before you print mileage!')
        form = UserSettingsForm(request.POST or None)
        return render(request, 'user/settings.html', {'form': form})
Run Code Online (Sandbox Code Playgroud)

我还有其他一些需要使用 a 的地方,redirect …

python django redirect messages django-messages

6
推荐指数
1
解决办法
7823
查看次数

在 docker-compose.yml 文件中指定用于 SSL 的证书?

我有一个docker-compose.yaml如下所示的小文件(它用于启动本地测试环境):

version: '2'

services:
    ubuntu:
        build:
            context: ./build
            dockerfile: ubuntu.dock
        volumes:
            - ./transfer:/home/
        ports:
            - "60000:22"
    python:
        build:
            context: ./build
            dockerfile: python.dock
        volumes:
            - .:/home/code
        links:
            - mssql
            - ubuntu
    mssql:
      image: "microsoft/mssql-server-linux"
      environment:
          SA_PASSWORD: "somepassword"
          ACCEPT_EULA: "Y"
      ports:
          - "1433:1433"
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,当我运行时docker-compose up,它在此步骤失败(位于文件中python.dock):

Step 10/19 : RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
 ---> Running in e4963c91a05b
Run Code Online (Sandbox Code Playgroud)

错误看起来像这样:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent …
Run Code Online (Sandbox Code Playgroud)

ssl curl docker docker-compose

5
推荐指数
1
解决办法
3万
查看次数

Django 子查询中注释内的注释?

我有一些模型,正在尝试加快列出用户的页面的速度。

问题是我正在利用模型方法来显示一些数据 - 但是当我列出用户时,它会多次访问数据库,最终UserUser导致数百个额外查询(当列表中有数千个对象时,会出现数千个查询) )所以这对性能造成了严重影响。

从那时起我就开始使用annotateand ,prefetch_related这大大减少了查询。我只是有点不知道如何注释。

我有一个模型方法(在Summation模型上),用于获取Evaluation用户的数据摘要,如下所示:

    def evaluations_summary(self):
        evaluations_summary = (
            self.evaluation_set.all()
            .values("evaluation_type__name")
            .annotate(Count("evaluation_type"))
        )
        return evaluations_summary
Run Code Online (Sandbox Code Playgroud)

我试图弄清楚如何注释对象上的特定查询User

因此,这种关系看起来User有多个Summations,但只有一个是“活动的”,这就是我们在列表中显示的那个User。每个Summation都有多个Evaluations- 我们也试图展示其摘要。

这里是代码相关部分的摘要(包括Summation模型方法,它给出了当前正在“工作”以根据需要显示数据的示例) - 我还制作了一个Pastebin 示例以便于查看。

# MODELS 
 
class User(AbstractUser):
    employee_no = models.IntegerField(default=1)
    ...all the other usual attributes...
 
class Summation(CreateUpdateMixin, CreateUpdateUserMixin):
    # CreateUpdateMixin adds 'created_at' & 'updated_at
    # CreateUpdateUserMixin adds 'created_by' & …
Run Code Online (Sandbox Code Playgroud)

python django django-models django-rest-framework django-annotate

5
推荐指数
0
解决办法
1010
查看次数

在 C# .NET 中使用服务帐户而不是个人帐户进行身份验证以使用 Google Sheets

我开发了一个应用程序,它使用了一些 Google 表格。

我能够弄清楚如何使用以下代码访问 Google Sheets API:

    UserCredential credential;
    using (var stream =
                  new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
    {
        string credPath = System.Environment.GetFolderPath(
            System.Environment.SpecialFolder.Personal);


        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore(credPath, true)).Result;
        Console.WriteLine("Credential file saved to: " + credPath);
    }
    // Create Google Sheets API service.
    var service = new SheetsService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });
Run Code Online (Sandbox Code Playgroud)

此应用程序将被其他一些人使用 - 但是当他们第一次运行该应用程序时,它会要求他们登录 Google - 但他们的帐户没有给他们适当的访问权限。

我认为(如果我错了,请纠正我) - 使用服务帐户应该可以解决我的问题,并且不再提示用户“登录”,但仍允许我的应用程序适当地读取/更新表格。

我想使用我现有的代码并修改它以使用服务帐户,但我找不到关于如何执行此操作的任何好的文档。我已经创建了服务帐户并将 ServiceAccount.json 文件与当前的“client_secret.json”文件放在同一个位置,但我不确定如何进一步进行。

我尝试将代码更改为:

    ServiceAccountCredential credential;
    //UserCredential credential;
    using (var …
Run Code Online (Sandbox Code Playgroud)

c# json service-accounts google-sheets-api

4
推荐指数
2
解决办法
3078
查看次数

反序列化JSON凭据Data C#Google表格API时出错

我目前正在尝试使用服务帐户访问GoogleSheets API - 我遇到的问题是我的.json文件.

这是我的代码:

    try
    {
        string[] scopes = new string[] { SheetsService.Scope.Spreadsheets, SheetsService.Scope.SpreadsheetsReadonly }; // Put your scopes here

        var stream = new FileStream("my_application_secret.json", FileMode.Open, FileAccess.Read);

        var credential = GoogleCredential.FromStream(stream);
        credential = credential.CreateScoped(scopes);

        SheetsService service = new SheetsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "myApplication",
        });
        return service;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Create service account myApplicationServiceAccount failed : " + ex.Message);
        throw new Exception("Create ServiceAccount Failed : ", ex);
    }
Run Code Online (Sandbox Code Playgroud)

这启动了我的错误,内容如下:

Create service account myApplicationServiceAccount failed …
Run Code Online (Sandbox Code Playgroud)

c# json google-api service-accounts google-sheets-api

4
推荐指数
1
解决办法
2026
查看次数

最快的一种列表,其中alpha首先在python中排序

我有一个简单的列表,其中数字是字符串:

simple_list = ['1','2','3','4','5','K','P']

我想首先用alpha对数据进行排序,然后用数字进行排序.

目前我在做:

# Probably a faster way to handle this
alpha_list = [x for x in simple_list if not x.isnumeric()]
grade_list = [x for x in simple_list if x.isnumeric()]
# Put the alpha grades at the beginning of the grade_list
if alpha_list:
    grade_list = sorted(alpha_list) + sorted(grade_list)
Run Code Online (Sandbox Code Playgroud)

我确信有一种更快的方法来解决这个问题 - 我似乎无法找到它.

我目前得到的结果是正确的 ['K','P','1','2','3','4','5']

我只是想知道是否有一种方法可以压缩所有那些比多列表理解更有效的方法.

python sorting list-comprehension python-3.x

4
推荐指数
1
解决办法
99
查看次数

Django 未在 404 页面上应用来自应用程序的 CSS 文件

Django 3.0.8

蟒蛇 3.7.x

我有一个带有一些应用程序的 Django 项目。我正在尝试为 400、403、404、500 错误创建一些“默认”错误页面。我已经完成并显示了适当的模板 - 但没有任何样式或 JS。

在 404 错误页面中,我尝试从其中一个应用程序链接到 CSS,以便应用正确的样式 - 但在控制台中,我看到此错误:

Refused to apply style from 'http://127.0.0.1:8000/static/launcher/dist/css/launcher.css' because of its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Run Code Online (Sandbox Code Playgroud)

但是,该文件存在于那里。

这个特定的 CSS 文件位于两个位置:在 app 目录中,它也位于 STATIC_ROOT 中,因为我运行了该python manage.py collectstatic命令。

STATIC_URL 设置为 /static/

CSS 文件位于:

  • project_dir/launcher/static/launcher/dist/css/launcher.css

  • project_dir/static/launcher/dist/css/launcher.css

我的 404 模板位于:

project_dir/templates/404.html

我的 CSS 链接如下所示:

<link rel="stylesheet" type="text/css" href="{% static 'launcher/dist/css/launcher.css' %}" />

我的项目网址如下所示:

urlpatterns = …
Run Code Online (Sandbox Code Playgroud)

html css python django django-templates

4
推荐指数
1
解决办法
1376
查看次数

File.Copy 错误 - C# - IOException 文件名、目录名或卷标

尝试将目录中的所有文件/目录复制到我创建的新位置。用户在组合框中选择要使用的“备份驱动器”,然后当他们单击备份桌面按钮时,它只会在该驱动器上创建一个备份目录并将所有文件复制到该目录中。

备份目录会在驱动器上适当地创建 - 但它遇到的第一个文件会引发错误。

private void backupDesktopButton_Click(object sender, EventArgs e)
{
     //set the destionationLocation to the selectedDrive
     string selectedDrive = backupDriveCombo.SelectedItem.ToString();
     string destinationLocation = selectedDrive+"Backups-" + DateTime.Now.Month.ToString()+"-"+DateTime.Now.Year.ToString()+"\\Desktop\\";
     if (!Directory.Exists(destinationLocation))
     {
         Directory.CreateDirectory(destinationLocation);
     }

     string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

     string[] fileList = Directory.GetFiles(desktopFolder);
     foreach (string file in fileList)
     {
         //move the file
         File.Copy(file, destinationLocation);
     }
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

IOException 未处理。

文件名、目录名或卷标语法不正确。

在“自动”窗口(VS2010)中,我看到位置设置正确:

destinationLocation = 适当的目录 ( C:\Backups-8-2016\Desktop\ )

file = 适当的第一个文件(C:\Users\myusername\Desktop\myshortcut.url

我错过了什么?我拥有能够复制/粘贴/创建事物的所有权利,并且创建了存储它的目录 - 只是移动文件的问题。

c#

3
推荐指数
2
解决办法
1万
查看次数