[Python] How to fetch data from an flaskapp and display it in a composable in jetpack compose?

Discussão em 'Python' iniciado por Stack, Fevereiro 2, 2025.

  1. Stack

    Stack Membro Participativo

    I have a flask app code that is written in python and I am trying to figure out how to fetch this code in jetpack compose when a button is clicked (Showing a matched person).The flask app uses an external api and is connected to a postgresql database. The postgresql database has an HTTP-based URLs which is connected to the compose app. The database is populated with users. How can I achieve this?

    Flask App code:

    @app.route('/matches', methods=['GET'])
    def get_all_matches():
    try:
    users = (
    db.session.query(UserData, RelationshipData)
    .join(RelationshipData, UserData.user_auth_id == RelationshipData.user_auth_id)
    .all()
    )

    all_matches = {}
    for user_data, user_rel in users:
    matches, error = get_user_matches(user_data.user_auth_id, limit=1)

    if matches and not error:
    all_matches[user_data.user_auth_id] = {
    'user': {
    'id': user_data.user_auth_id,
    'firstname': user_data.firstname,
    'lastname': user_data.lastname,
    'gender': user_data.gender
    },
    'best_match': matches[0] if matches else None
    }

    return jsonify({'matches': all_matches}), 200

    except Exception as e:
    return jsonify({'error': str(e)}), 500


    Jetpack compose:

    MatchData:

    @Serializable
    data class User(
    val id: String,
    val firstname: String,
    val lastname: String,
    val gender: String
    )

    @Keep
    @Entity(tableName = "matches", indices = [Index(value = ["id"], unique = true)])
    @Serializable
    data class MatchData(
    val user: User,
    val best_match: User?
    )

    @Serializable
    data class MatchResponse(
    val matches: Map<String, MatchData>
    )



    Interface:

    interface UserService {

    @GET("matches")
    fun getAllMatches(): Call<MatchResponse>
    }



    MatchViewModel:

    @HiltViewModel
    class MatchViewModel @Inject constructor(
    private val userService: UserService
    ) : ViewModel() {

    private val _matches = mutableStateOf<Map<String, MatchData>?>(null)
    val matches: State<Map<String, MatchData>?> = _matches

    private val _error = mutableStateOf<String?>(null)
    val error: State<String?> = _error

    fun fetchMatches() {
    userService.getAllMatches().enqueue(object : Callback<MatchResponse> {
    override fun onResponse(call: Call<MatchResponse>, response: Response<MatchResponse>) {
    if (response.isSuccessful) {
    _matches.value = response.body()?.matches
    } else {
    _error.value = "Error: ${response.code()}"
    }
    }

    override fun onFailure(call: Call<MatchResponse>, t: Throwable) {
    _error.value = "Failed to fetch data: ${t.message}"
    }
    })
    }
    }

    Continue reading...

Compartilhe esta Página