Python Jsonify返回文本/HTML。

huangapple go评论54阅读模式
英文:

Python Jsonify returns text/html

问题

以下是您要翻译的代码部分:

class Fixture:
    def __init__(self, matchday, date, home_team, away_team, predicted_winner, spread):
        self.matchday = matchday
        self.date = date
        self.home_team = home_team
        self.away_team = away_team
        self.predicted_winner = predicted_winner
        self.spread = spread

import json

class League:
    def __init__(self, name, fixtures):
        self.name = name
        self.fixtures = fixtures

    def to_dict(self):
        return {
            "name": self.name,
            "fixtures": [fixture.to_dict() for fixture in self.fixtures]
        }

class LeagueEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, League):
            return {
                "name": obj.name,
                "fixtures": [fixture.__dict__ for fixture in obj.fixtures]
            }
        return super().default(obj)
from flask import Flask, Response, jsonify
from services import results_calculator

app = Flask(__name__)

@app.route('/results/<date_from>/<date_to>')
def get_results(date_from, date_to):
    fixture_results = results_calculator.calculate_results(date_from, date_to)
    return Response(jsonify(fixture_results), mimetype='application/json')

if __name__ == '__main__':
    app.run()
List<LeagueFixtures> fixtures = webClient
    .get()
    .uri(requestUri)
    .accept(MediaType.valueOf("application/json"))
    .retrieve()
    .bodyToMono(List.class)
    .block();
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class LeagueFixtures {
    private String name;
    private List<Fixture> fixtures;
}
package com.footballpredictor.predictoragent.model.input;

import lombok.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Fixture {
    private String date;
    private Long matchday;
    private String home_team;
    private String away_team;
    private String predicted_winner;
    private Double spread;
}

请注意,我已经忽略了不需要翻译的部分,并只返回了您要求翻译的代码段。如果您需要进一步的帮助或解答问题,请随时提出。

英文:

I have a python application which returns a bunch of league fixtures:

class Fixture:
    def __init__(self, matchday, date, home_team, away_team, predicted_winner, spread):
        self.matchday = matchday
        self.date = date
        self.home_team = home_team
        self.away_team = away_team
        self.predicted_winner = predicted_winner
        self.spread = spread
import json


class League:
    def __init__(self, name, fixtures):
        self.name = name
        self.fixtures = fixtures

    def to_dict(self):
        return {
            &quot;name&quot;: self.name,
            &quot;fixtures&quot;: [fixture.to_dict() for fixture in self.fixtures]
        }

class LeagueEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, League):
            return {
                &quot;name&quot;: obj.name,
                &quot;fixtures&quot;: [fixture.__dict__ for fixture in obj.fixtures]
            }
        return super().default(obj)

These objects are returned from a Flask API using jsonify:

from flask import Flask, Response, jsonify
from services import results_calculator

app = Flask(__name__)

@app.get(&#39;/results/&lt;date_from&gt;/&lt;date_to&gt;&#39;)
def get_results(date_from, date_to):
    fixture_results = results_calculator.calculate_results(date_from, date_to)
    return Response(jsonify(fixture_results), mimetype=&#39;application/json&#39;)

if __name__ == &#39;__main__&#39;:
  app.run()

I have a Java application which invokes this endpoint:

List&lt;LeagueFixtures&gt; fixtures = webClient
    .get()
    .uri(requestUri)
    .accept(MediaType.valueOf(&quot;application/json&quot;))
    .retrieve()
    .bodyToMono(List.class)
    .block();
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class LeagueFixtures {
    private String name;
    private List&lt;Fixture&gt; fixtures;
}
package com.footballpredictor.predictoragent.model.input;

import lombok.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Fixture {
    private String date;
    private Long matchday;
    private String home_team;
    private String away_team;
    private String predicted_winner;
    private Double spread;
}

However when the code hits, I get the following error:

> org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/html;charset=utf-8' not supported for bodyType=java.util.List<?>
at org.springframework.web.reactive.function.BodyExtractors.readWithMessageReaders(BodyExtractors.java:205) ~[spring-webflux-6.0.10.jar:6.0.10]
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
*__checkpoint ⇢ Body from GET http://localhost:5000/results/2023-06-02/2023-06-05 [DefaultClientResponse]

Am I missing something that is causing the jsonify function to be ignored?

In the flask API I have tried:

答案1

得分: 1

这不是你应该使用 jsonify 的方式,正如 jsonify 文档 所示

它将JSON输出转换为带有 application/json mimetype 的响应对象。

因此,你应该这样使用它

return jsonify(fixture_results)
英文:

This

return Response(jsonify(fixture_results), mimetype=&#39;application/json&#39;)

is not how you are supposed to use jsonify, as jsonify docs reveals

> It turns the JSON output into a Response object with the
> application/json mimetype.

So you should use it following way

return jsonify(fixture_results)

huangapple
  • 本文由 发表于 2023年7月11日 02:56:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76656573.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定