小编Hen*_*ody的帖子

python请求随JSONDecodeError随机中断

我已经调试了几个小时,为什么我的代码随机因此错误而中断: JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这是我的代码:

while True:
    try:
        submissions = requests.get('http://reymisterio.net/data-dump/api.php/submission?filter[]=form,cs,'+client+'&filter[]=date,cs,'+since).json()['submission']['records']
        break
    except requests.exceptions.ConnectionError:
        time.sleep(100)
Run Code Online (Sandbox Code Playgroud)

而且我一直在通过打印进行调试,requests.get(url)并且requests.get(url).text遇到了以下“特殊”情况:

  1. requests.get(url)返回成功的200响应并requests.get(url).text返回html。我已经在线阅读了使用时应该会失败的信息requests.get(url).json(),因为它无法读取html,但是以某种方式不会损坏。为什么是这样?

  2. requests.get(url)返回成功的200响应,并且requests.get(url).text为json格式。我不明白为什么到requests.get(url).json()JSONDecodeError时会中断?

requests.get(url).text情况2 的确切值为:

{
  "submission": {
    "columns": [
      "pk",
      "form",
      "date",
      "ip"
    ],
    "records": [
      [
        "21197",
        "mistico-form-contacto-form",
        "2018-09-21 09:04:41",
        "186.179.71.106"
      ]
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

python json python-requests jsondecoder

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

Golang、postgresql、go-pg、UNION ALL 和 WITH

I\xe2\x80\x99m 使用 Golang、PostgreSQL 和 go-pg ( https://github.com/go-pg/pg )。

\n\n

我需要这个查询:

\n\n
WITH cte AS (\n    SELECT\n        "player"."id",\n        "player"."created_at",\n        "player"."note"\n    FROM\n        "players" AS "player"\n    ORDER BY\n        "amount" DESC,\n        "id"\n        LIMIT 5\n    ) ( SELECT * FROM cte ) UNION ALL\n    (\n    SELECT\n        "id",\n        "created_at",\n        CONCAT_WS ( \'|\', LAST_VALUE ( "created_at" ) OVER ( ), LAST_VALUE ( "id" ) OVER ( ) ) AS note\n    FROM\n        cte -- THIS IS CORRECT\n    LIMIT 1\n    )\n
Run Code Online (Sandbox Code Playgroud)\n\n

相反go-pg一直给我这个:

\n\n
WITH "cte" AS …
Run Code Online (Sandbox Code Playgroud)

sql postgresql union go go-pg

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

在 Go 中解组通用 json

我是一名新的 Go 程序员(来自 Java),我想重现一种在 Java 中易于使用的通用方式。

我想创建一些函数,允许我对 JSON 字符串执行解组,以避免代码重复。

这是我当前不起作用的代码:

type myStruct1 struct {
    id string
    name string
}

func (obj myStruct1) toString() string {
    var result bytes.Buffer
    result.WriteString("id : ")
    result.WriteString(obj.id)
    result.WriteString("\n")
    result.WriteString("name : ")
    result.WriteString(obj.name)

    return result.String()
}

func main() {

    content := `{id:"id1",name="myName"}`
    object := myStruct1{}
    parseJSON(content, object)

    fmt.Println(object.toString()) 
}

func parseJSON(content string, object interface{}) {
    var parsed interface{}
    json.Unmarshal([]byte(content), &parsed)
}
Run Code Online (Sandbox Code Playgroud)

这段代码在运行时返回给我:

id : 
name : 
Run Code Online (Sandbox Code Playgroud)

你有什么主意吗 ?

谢谢

json go

4
推荐指数
3
解决办法
9590
查看次数

ReactJs 安全性

I have just started learning authorization and authentication in react, and I'm writing this after finishing my first simple login system using JWT, as most of you know you store a token in the browser and then you compare it with the saved tokens in your backend now when that validation is done truly I set Authenticated Boolean to true and gain access to the website, after finishing that simple system I checked react dev tools and I found out …

security web reactjs

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

是否可以在 TypeScript 中传播独特的泛型类型?

是否可以将函数的参数分散到泛型类型数组中?

我正在尝试将 TypeScript 类型添加到接受函数并返回函数的通用函数。传递的函数的参数与返回的函数的参数相关。我希望消费者能够向传入的函数添加类型,并使这些类型出现在返回的函数上。

我已经找到了该问题的基本解决方案,但它仅适用于固定数量的参数。是否可以通过以下方式传播通用参数?

用法示例:

type Foo = // Generic solution here

const bar = foo((state, name: string, age: number));

bar('John', 22); // All good
bar('John', 'Doe'); // Type Error, 'Doe' is not a number

const baz = foo((state, firstName: string, lastName: string, age: number));

baz('John', 'Doe', 22)
Run Code Online (Sandbox Code Playgroud)

这是用于 React Hook 集成。有一些非常好的例子,提供商在让 TypeScript 类型安全对于消费者来说非常容易方面做得非常出色。TypedUseSelectorHookReact Redux 就是一个很好的例子。https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-redux/index.d.ts#L556

尝试 1 一种带有扩散的解决方案。但不幸的是,所有类型都是所有可能类型的联合。

export type foo<State> = <Args>(
    baz: (state: State, ...args: Args[]) => Partial<State>
) => (...args: Args[]) => …
Run Code Online (Sandbox Code Playgroud)

typescript

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

使用 Django 在 Google App Engine Flexible 上永久重定向 http 到 https

我正在使用 Django 在 Python 3 灵活环境中使用 Google Cloud Platform 的 App Engine 开发一个项目,我正在尝试将所有请求永久重定向http到https所有路由,但到目前为止还没有成功。我可以通过 访问该站点https,但前提是明确写在地址栏中。

我看过这篇文章:如何将`http://`和`www.` URLs永久重定向到`https://`?但没有发现答案有用。

除了重定向之外,该应用程序在各个方面都可以正常工作。这是我的app.yaml文件:

# [START runtime]
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT myproject.wsgi

runtime_config:
  python_version: 3
# [END runtime]
Run Code Online (Sandbox Code Playgroud)

在myproject/settings.py我定义了这些变量:

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ('HTTP-X-FORWARDED-PROTO', 'https')
Run Code Online (Sandbox Code Playgroud)

在我的本地机器上,当我设置SECURE_SSL_REDIRECT为 时True,我被https正确重定向到,即使 localhost 不支持 SSL。在生产中,我仍然可以仅使用http.

是否有什么我遗漏或做错的事情导致重定向不发生?

python django ssl google-app-engine google-cloud-platform

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

将组件键设置为等于 Route 中的路径参数

我有一个定义如下的路线:

<Route exact path="/licenses/:type?" component={Licenses} />
Run Code Online (Sandbox Code Playgroud)

我希望我的组件在类型参数更改时重新渲染,因此,如 react-router 文档中所述,我需要使用一个键。我想要与传递给路由的参数相同的键值。就像是:

<Route exact path="/licenses/:type?" key=":type" component={Licenses} />
Run Code Online (Sandbox Code Playgroud)

但是我无法获取类型参数的值作为键。有没有办法将键设置为与类型参数的值相同?

javascript reactjs react-router

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

如何为 react-bootstrap 的活动选项卡切换 css 类?

我正在尝试向活动选项卡添加自定义样式,但不知道如何切换活动选项卡的样式类。

以下是我的代码:

import React, { useState } from "react";
import "./styles.css";
import { Container, Row, Col, Tab, Nav } from "react-bootstrap";

export default function App() {
  const [key, setKey] = useState("first");

  const ActiveStyle = {
    textAlign: "center",
    background: "white",
    borderRadius: "2em",
    padding: " 0.3em 1.5em",
    letterSpacing: "0.2em"
  };

  const inActiveStyle = {
    ...ActiveStyle,
    background: "transparent",
    "border-color": "transparent",
    color: "inherit"
  };

  return (
    <div className="App">
      <Container style={{ width: "auto" }}>
        <Tab.Container activeKey={key} onSelect={key => setKey(key)}>
          <Row style={{ padding: "1em 1em", background: …
Run Code Online (Sandbox Code Playgroud)

reactjs react-bootstrap

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

useEffect 仅当状态改变时

我有useEffect哪个调用actionfromredux来获取上传

useEffect(() => {
    getUploads()
}, [getUploads])
Run Code Online (Sandbox Code Playgroud)

但是,我只想在状态更改时获取,而不是每次组件呈现时获取。我已经将状态映射为:

{filteredUploads.map((image, i) => { return (...) })}
Run Code Online (Sandbox Code Playgroud)

我试图添加getUploads, filteredUploads,filteredUploads.length作为依赖数组。它都没有奏效。

我的redux-action:

export const getUploads = () => async dispatch => {
    try {
        dispatch({ type: 'LOADING', payload: true })

        const res = await axios.get('/uploads/myuploads')
        dispatch({
            type: GETMYUPLOAD_SUCCESS,
            payload: res.data
        })

    } catch (err) {
        const error = err.response.data.error[0].msg

        dispatch(setAlert(error, 'danger'))
    }
}
Run Code Online (Sandbox Code Playgroud)

mapStatetoProps:

function mapStateToProps(state) {
    const { myuploads, …
Run Code Online (Sandbox Code Playgroud)

reactjs redux react-hooks use-effect

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

根据 TypeScript 中的查找类型限制通用键类型

我正在开发一个带有两个类型参数的函数,T并且K. T扩展一个Record类型并且K是第一种类型的键。有没有办法可以根据其查找类型 ( T[K]) 来限制键类型T?

我有以下类型:

type FormValue = string | number | boolean | null;

type FormValues = Record<string, FormValue>;
Run Code Online (Sandbox Code Playgroud)

以及以下函数:

function numericFormHelperFunc<T extends FormValues, K extends keyof T>(key: K, formValues: T) {}
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以限制哪些键可用于此功能,以便只允许formValues具有查找类型的键?number基本上是断言的一种方式T[K] extends number。

例如,如果我有这个示例表单类型:

type MyFormValues = {
    name: string;
    age: number;
    numPets: number;
}
Run Code Online (Sandbox Code Playgroud)

我可以添加类型限制,以便仅可以使用numericFormHelperFunc键"age"和吗?"numPets"

我正在寻找一种静态方法来执行此操作,以便我会收到有关尝试使用numericFormHelperFunc("name", myFormValues). 还希望打字稿知道查找的值key是 …

generics types typescript typescript-generics

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