]> git.ipfire.org Git - people/ms/libloc.git/blame - src/python/database.c
python: Add Database class
[people/ms/libloc.git] / src / python / database.c
CommitLineData
9cdf6c53
MT
1/*
2 libloc - A library to determine the location of someone on the Internet
3
4 Copyright (C) 2017 IPFire Development Team <info@ipfire.org>
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15*/
16
17#include <Python.h>
18
19#include "../database.h"
20#include "database.h"
21
22static PyObject* Database_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {
23 // Create libloc context
24 struct loc_ctx* ctx;
25 int r = loc_new(&ctx);
26 if (r)
27 return NULL;
28
29 DatabaseObject* self = (DatabaseObject*)type->tp_alloc(type, 0);
30 if (self) {
31 self->ctx = ctx;
32 }
33
34 return (PyObject*)self;
35}
36
37static void Database_dealloc(DatabaseObject* self) {
38 if (self->db)
39 loc_database_unref(self->db);
40
41 if (self->ctx)
42 loc_unref(self->ctx);
43
44 Py_TYPE(self)->tp_free((PyObject* )self);
45}
46
47static int Database_init(DatabaseObject* self, PyObject* args, PyObject* kwargs) {
48 const char* path = NULL;
49
50 if (!PyArg_ParseTuple(args, "s", &path))
51 return -1;
52
53 // Open the file for reading
54 FILE* f = fopen(path, "r");
55 if (!f)
56 return -1;
57
58 // Load the database
59 int r = loc_database_new(self->ctx, &self->db, f);
60 fclose(f);
61
62 // Return on any errors
63 if (r)
64 return -1;
65
66 return 0;
67}
68
69static struct PyMethodDef Database_methods[] = {
70 { NULL },
71};
72
73PyTypeObject DatabaseType = {
74 PyVarObject_HEAD_INIT(NULL, 0)
75 tp_name: "location.Database",
76 tp_basicsize: sizeof(DatabaseObject),
77 tp_flags: Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
78 tp_new: Database_new,
79 tp_dealloc: (destructor)Database_dealloc,
80 tp_init: (initproc)Database_init,
81 tp_doc: "Database object",
82 tp_methods: Database_methods,
83};