Esempio n. 1
0
static PyObject *pyketama_Continuum_repr(PyObject *o) {
    PyObject *r;

    r = PyString_FromFormat("<%s from ", o->ob_type->tp_name);
    PyString_Concat(&r,PyObject_Repr(
        PyString_FromString(((pyketama_Continuum* )o)->filename)));
    if (r) {
        PyString_Concat(&r, PyString_FromString(">"));
    }

    /* Example: <ketama.Continuum from '/tmp/slist'> */
    return r;
}
Esempio n. 2
0
//! Returns method's signature
char *
script_signature(const char *model, const char *member, int direction)
{
    /*!
     * Returns method's signature
     *
     * @model Model name
     * @member Member nam
     * @direction 0 for input, 1 for output
     * @return Signature
     *
     */

    PyObject *py_models = PyDict_GetItemString(py_core, "models");
    PyObject *py_model = PyDict_GetItemString(py_models, model);
    PyObject *py_method = PyDict_GetItemString(py_model, member);
    PyObject *py_str = PyString_FromString("");
    PyObject *py_list;

    if (direction == 0) {
        py_list = PyTuple_GetItem(py_method, 2);
    }
    else {
        py_list = PyTuple_GetItem(py_method, 3);
    }

    int i;
    for (i = 0; i < PyList_Size(py_list); i++) {
        PyString_Concat(&py_str, PyList_GetItem(py_list, i));
    }

    return PyString_AsString(py_str);
}
Esempio n. 3
0
static PyObject *
slice_repr(PySliceObject *r)
{
	PyObject *s, *comma;

	s = PyString_FromString("slice(");
	comma = PyString_FromString(", ");
	PyString_ConcatAndDel(&s, PyObject_Repr(r->start));
	PyString_Concat(&s, comma);
	PyString_ConcatAndDel(&s, PyObject_Repr(r->stop));
	PyString_Concat(&s, comma);
	PyString_ConcatAndDel(&s, PyObject_Repr(r->step));
	PyString_ConcatAndDel(&s, PyString_FromString(")"));
	Py_DECREF(comma);
	return s;
}
bool BINARY_OPERATION_ADD_STR_STR_INPLACE(PyObject **operand1, PyObject *operand2) {
    assert(operand1);
    CHECK_OBJECT(*operand1);
    CHECK_OBJECT(operand2);
    assert(PyString_CheckExact(*operand1));
    assert(PyString_CheckExact(operand2));

    if (!PyString_CHECK_INTERNED(*operand1) && Py_REFCNT(*operand1) == 1) {
        return STRING_ADD_INCREMENTAL(operand1, operand2);
    }

    PyString_Concat(operand1, operand2);
    return !ERROR_OCCURRED();

    PyObject *result = PyNumber_InPlaceAdd(*operand1, operand2);

    if (unlikely(result == NULL)) {
        return false;
    }

    // We got an object handed, that we have to release.
    Py_DECREF(*operand1);

    // That's our return value then. As we use a dedicated variable, it's
    // OK that way.
    *operand1 = result;

    return true;
}
Esempio n. 5
0
void set_dyn_pyhome(char *home, uint16_t pyhome_len) {


	char venv_version[15];
	PyObject *site_module;

	PyObject *pysys_dict = get_uwsgi_pydict("sys");

	PyObject *pypath = PyDict_GetItemString(pysys_dict, "path");
	if (!pypath) {
		PyErr_Print();
		exit(1);
	}

        // simulate a pythonhome directive
        if (uwsgi.wsgi_req->home_len > 0) {

                PyObject *venv_path = UWSGI_PYFROMSTRINGSIZE(uwsgi.wsgi_req->home, uwsgi.wsgi_req->home_len);

#ifdef UWSGI_DEBUG
                uwsgi_debug("setting dynamic virtualenv to %.*s\n", uwsgi.wsgi_req->home_len, uwsgi.wsgi_req->home);
#endif

                PyDict_SetItemString(pysys_dict, "prefix", venv_path);
                PyDict_SetItemString(pysys_dict, "exec_prefix", venv_path);

                venv_version[14] = 0;
                if (snprintf(venv_version, 15, "/lib/python%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION) == -1) {
                        return;
                }

                // check here
                PyString_Concat(&venv_path, PyString_FromString(venv_version));

                if (PyList_Insert(pypath, 0, venv_path)) {
                        PyErr_Print();
                }

                site_module = PyImport_ImportModule("site");
                if (site_module) {
                        PyImport_ReloadModule(site_module);
                }

        }
}
Esempio n. 6
0
bool concat(PyObject** val1, PyObject* val2)
{
    if (PyUnicode_Check(*val1) && PyUnicode_Check(val2)) {
        PyObject* result = PyUnicode_Concat(*val1, val2);
        Py_DECREF(*val1);
        *val1 = result;
        return true;
    }

    if (PyBytes_Check(*val1) && PyBytes_Check(val2)) {
        PyBytes_Concat(val1, val2);
        return true;
    }

#if PY_MAJOR_VERSION < 3
    if (PyString_Check(*val1) && PyString_Check(val2)) {
        PyString_Concat(val1, val2);
        return true;
    }
#endif
    return false;
}
Esempio n. 7
0
PyObject * Field_str ( Field * self )
{
    PyObject * pyobj,
             * string,
             * typeobj;

    if ( ! ( string = PyString_FromFormat ( "Field[" ) ) )
        return 0;

    /* Output the field name - if present */
    if ( self->field.flags & FUDGE_FIELD_HAS_NAME )
    {
        PyObject * namestr,
                 * nameobj = Field_name ( self );
        if ( ! nameobj )
            goto clear_string_and_fail;

        namestr = PyObject_Str ( nameobj );
        Py_DECREF( nameobj );
        if ( ! namestr )
            goto clear_string_and_fail;

        PyString_ConcatAndDel ( &string, namestr );
        if ( ! string )
            return 0;
    }

    /* Separator between name and ordinal */
    PyString_ConcatAndDel ( &string, PyString_FromString ( "|" ) );
    if ( ! string )
        return 0;

    /* Output the field ordinal - if present */
    if ( self->field.flags & FUDGE_FIELD_HAS_ORDINAL )
    {
        PyString_ConcatAndDel ( &string, PyString_FromFormat (
                                             "%d", self->field.ordinal ) );
        if ( ! string )
            return 0;
    }

    /* Separator between ordinal and type name */
    PyString_ConcatAndDel ( &string, PyString_FromString ( "|" ) );
    if ( ! string )
        return 0;

    /* Retrieve the type name from the lookup in the types module; if
     * unknown, display the type id */
    if ( ! ( typeobj = PyInt_FromLong ( self->field.type ) ) )
        goto clear_string_and_fail;
    pyobj = PyDict_GetItem ( s_typenamedict, typeobj );
    Py_DECREF( typeobj );
    if ( pyobj )
        PyString_Concat ( &string, pyobj );
    else
        PyString_ConcatAndDel ( &string,
                                PyString_FromFormat ( "%d", self->field.type ) );
    if ( ! string )
        return 0;

    /* Separator between type name and the value */
    PyString_ConcatAndDel ( &string, PyString_FromString ( ":" ) );
    if ( ! string )
        return 0;

    /* Output the stringized field value */
    switch ( self->field.type )
    {
        case FUDGE_TYPE_INDICATOR:
            break;

        /* For all non-byte array types, use the stringized Python value */
        case FUDGE_TYPE_BOOLEAN:
        case FUDGE_TYPE_BYTE:
        case FUDGE_TYPE_SHORT:
        case FUDGE_TYPE_INT:
        case FUDGE_TYPE_LONG:
        case FUDGE_TYPE_FLOAT:
        case FUDGE_TYPE_DOUBLE:
        case FUDGE_TYPE_SHORT_ARRAY:
        case FUDGE_TYPE_INT_ARRAY:
        case FUDGE_TYPE_LONG_ARRAY:
        case FUDGE_TYPE_FLOAT_ARRAY:
        case FUDGE_TYPE_DOUBLE_ARRAY:
        case FUDGE_TYPE_STRING:
        case FUDGE_TYPE_FUDGE_MSG:
        case FUDGE_TYPE_DATE:
        case FUDGE_TYPE_TIME:
        case FUDGE_TYPE_DATETIME:
            if ( ! ( pyobj = Field_value ( self ) ) )
                goto clear_string_and_fail;
            PyString_ConcatAndDel ( &string, PyObject_Str ( pyobj ) );
            Py_DECREF( pyobj );
            break;

        /* Assume everything else is just a bundle of (potentially
         * unprintable) bytes */
        default:
            PyString_ConcatAndDel ( &string,
                                    PyString_FromFormat ( "<%d bytes>",
                                                          self->field.numbytes ) );
            break;
    }

    if ( string )
        PyString_ConcatAndDel ( &string, PyString_FromString ( "]" ) );
    return string;

clear_string_and_fail:
    Py_XDECREF( string );
    return 0;
}
Esempio n. 8
0
NUITKA_MAY_BE_UNUSED static bool BINARY_OPERATION_ADD_INPLACE( PyObject **operand1, PyObject *operand2 )
{
    assert( operand1 );
    CHECK_OBJECT( *operand1 );
    CHECK_OBJECT( operand2 );

#if PYTHON_VERSION < 300
    // Something similar for Python3 should exist too.
    if ( PyInt_CheckExact( *operand1 ) && PyInt_CheckExact( operand2 ) )
    {
        long a, b, i;

        a = PyInt_AS_LONG( *operand1 );
        b = PyInt_AS_LONG( operand2 );

        i = a + b;

        // Detect overflow, in which case, a "long" object would have to be
        // created, which we won't handle here. TODO: Add an else for that
        // case.
        if (likely(!( (i^a) < 0 && (i^b) < 0 ) ))
        {
            PyObject *result = PyInt_FromLong( i );
            Py_DECREF( *operand1 );

            *operand1 = result;

            return true;
        }
    }
#endif

#if PYTHON_VERSION < 300
    if ( Py_REFCNT( *operand1 ) == 1 )
    {
        // We more or less own the operand, so we might re-use its storage and
        // execute stuff in-place.
        if ( PyString_CheckExact( *operand1 ) &&
             !PyString_CHECK_INTERNED( *operand1 ) &&
             PyString_CheckExact( operand2 ) )
        {
            return STRING_ADD_INCREMENTAL( operand1, operand2 );
        }
        else if ( PyFloat_CheckExact( *operand1 ) &&
                  PyFloat_CheckExact( operand2 ) )
        {
            return FLOAT_ADD_INCREMENTAL( operand1, operand2 );

        }
    }

    // Strings are to be treated differently.
    if ( PyString_CheckExact( *operand1 ) && PyString_CheckExact( operand2 ) )
    {
        PyString_Concat( operand1, operand2 );
        return !ERROR_OCCURRED();
    }
#else
    if ( Py_REFCNT( *operand1 ) == 1 )
    {
        // We more or less own the operand, so we might re-use its storage and
        // execute stuff in-place.
        if ( PyUnicode_CheckExact( *operand1 ) &&
             !PyUnicode_CHECK_INTERNED( *operand1 ) &&
             PyUnicode_CheckExact( operand2 ) )
        {
            return UNICODE_ADD_INCREMENTAL( operand1, operand2 );
        }
        else if ( PyFloat_CheckExact( *operand1 ) &&
                  PyFloat_CheckExact( operand2 ) )
        {
            return FLOAT_ADD_INCREMENTAL( operand1, operand2 );
        }
    }

    // Strings are to be treated differently.
    if ( PyUnicode_CheckExact( *operand1 ) && PyUnicode_CheckExact( operand2 ) )
    {
        PyObject *result = PyUnicode_Concat( *operand1, operand2 );

        if (unlikely( result == NULL ))
        {
            return false;
        }

        Py_DECREF( *operand1 );
        *operand1 = result;

        return true;
    }
#endif

    PyObject *result = PyNumber_InPlaceAdd( *operand1, operand2 );

    if (unlikely( result == NULL ))
    {
        return false;
    }

    // We got an object handed, that we have to release.
    Py_DECREF( *operand1 );

    // That's our return value then. As we use a dedicated variable, it's
    // OK that way.
    *operand1 = result;

    return true;
}
Esempio n. 9
0
/*
This is the main python handler that will transform and treat the client html request. 
return 1 if we have found a python object to treat the requested uri
return 0 if not (page not found)
return -1 in case of problem
return -2 in case the request command is not implemented
*/
int python_handler(struct client *cli)
{
    PyObject *pydict, *pydummy;
    int ret;

    if (debug)
         printf("host=%s,port=%i:python_handler:HEADER:\n%s**\n", cli->remote_addr, cli->remote_port, cli->input_header);
    //  1)initialise environ
    PyObject *pyenviron_class=PyObject_GetAttrString(py_base_module, "Environ");
    if (!pyenviron_class)
    {
         printf("load Environ failed from base module");
         exit(1);
    }
    PyObject *pyenviron=PyObject_CallObject(pyenviron_class, NULL);
    if (!pyenviron)
    {
         printf("Failed to create an instance of Environ");
         exit(1);
    }
    Py_DECREF(pyenviron_class);
    //  2)transform headers into a dictionary and send it to environ.update_headers
    pydict=header_to_dict(cli);
    if (pydict==Py_None)
    {
        Py_DECREF(pyenviron);
        return -500;
    }
    update_environ(pyenviron, pydict, "update_headers");
    Py_DECREF(pydict);   
    //  2bis) we check if the request method is supported
    PyObject *pysupportedhttpcmd = PyObject_GetAttrString(py_base_module, "supported_HTTP_command");
    if (cli->cmd==NULL) pydummy=Py_None; 
    else pydummy = PyString_FromString(cli->cmd);
    if (PySequence_Contains(pysupportedhttpcmd,pydummy)!=1)
    {
        //return not implemented 
        Py_DECREF(pysupportedhttpcmd);
        Py_DECREF(pydummy);
        Py_DECREF(pyenviron);
        return -501;
    }
    Py_DECREF(pydummy);
    //  2ter) we treat directly the OPTIONS command
    if (strcmp(cli->cmd,"OPTIONS")==0)
    {
        pydummy=PyString_FromFormat("HTTP/1.0 200 OK\r\nServer: %s\r\nAllow: ", VERSION) ;
        PyObject *pyitem; 
        int index, max;
        max = PyList_Size(pysupportedhttpcmd);
        for (index=0; index<max; index++)
        {
            pyitem=PyList_GetItem(pysupportedhttpcmd, index);  // no need to decref pyitem
            PyString_Concat(&pydummy, PyObject_Str(pyitem));
            if (index<max-1)
               PyString_Concat(&pydummy, PyString_FromString(", "));
        }
        PyString_Concat(&pydummy, PyString_FromString("\r\nContent-Length: 0\r\n\r\n"));
        cli->response_header = PyString_AsString(pydummy);
	cli->response_header_length=(int)PyString_Size(pydummy);
        cli->response_content=PyList_New(0);
        Py_DECREF(pyenviron);
        return 1;
    }
    Py_DECREF(pysupportedhttpcmd);
    //  3)find if the uri is registered
    if (handle_uri(cli)!=1)
    {
         if (py_generic_cb==NULL)
         {
            //printf("uri not found\n");
            Py_DECREF(pyenviron);
            return 0;
         }
         else
         {
             cli->wsgi_cb=py_generic_cb;
             Py_INCREF(cli->wsgi_cb);
             cli->uri_path=(char *)calloc(1, sizeof(char));
             strcpy(cli->uri_path,"");
         }
    }
    // 4) build path_info, ...
    pydict=py_build_method_variables(cli);
    update_environ(pyenviron, pydict, "update_uri");
    Py_DECREF(pydict);   
    // 5) in case of POST, put it into the wsgi.input
    if (strcmp(cli->cmd,"POST")==0)
    {
        ret=manage_header_body(cli, pyenviron);
        if (ret < 0) {
            return ret;
        }
    }
    //  6) add some request info
    pydict=py_get_request_info(cli);
    update_environ(pyenviron, pydict, "update_from_request");
    Py_DECREF(pydict);
    // 7) build response object
    PyObject *pystart_response_class=PyObject_GetAttrString(py_base_module, "Start_response");
    PyObject *pystart_response=PyInstance_New(pystart_response_class, NULL, NULL);
    Py_DECREF(pystart_response_class);
    if (PyErr_Occurred()) 
    {
             PyErr_Print();
             return -500;
    }
    // 7b) add the current date to the response object
    PyObject *py_response_header=PyObject_GetAttrString(pystart_response,"response_headers");
    char *sftime;
    sftime=cur_time_rfc1123();
    pydummy = PyString_FromString(sftime);
    PyDict_SetItemString(py_response_header, "Date", pydummy);
    Py_DECREF(pydummy);
    Py_DECREF(py_response_header);
    free(sftime);
    pydummy = PyString_FromString(VERSION);
    PyDict_SetItemString(py_response_header, "Server", pydummy);
    Py_DECREF(pydummy);
    
    // 8) execute python callbacks with his parameters
    PyObject *pyarglist = Py_BuildValue("(OO)", pyenviron, pystart_response );
    cli->response_content = PyEval_CallObject(cli->wsgi_cb,pyarglist);
    if (cli->response_content!=NULL) 
    {
        if ((PyFile_Check(cli->response_content)==0) && (PyIter_Check(cli->response_content)==1)) {
            //This is an Iterator object. We have to execute it first
            cli->response_content_obj = cli->response_content;
            cli->response_content = PyIter_Next(cli->response_content_obj);
        }
    }
    Py_DECREF(pyarglist);
    Py_XDECREF(cli->wsgi_cb);
    if (cli->response_content!=NULL) 
    {
        PyObject *pydummy = PyObject_Str(pystart_response);
        cli->response_header = PyString_AsString(pydummy);
	cli->response_header_length = (int)PyString_Size(pydummy);
        Py_DECREF(pydummy);
    }
    else 
    //python call return is NULL
    {
        printf("Python error!!!\n");
        char buff[200];
        sprintf(buff, "HTTP/1.0 500 Not found\r\nContent-Type: text/html\r\nServer: %s* \r\n\r\n", VERSION);
        cli->response_header = buff;

        if (cli->response_header == NULL)
        {
            printf("ERROR!!!! Memory allocation error in the Python error handling procedure\n");
            cli->response_header_length=0;
            goto leave_python_handler;
        } 	
        cli->response_header_length=strlen(cli->response_header);
        
        if (PyErr_Occurred()) 
        { 
             //get_traceback();py_b
             PyObject *pyerrormsg_method=PyObject_GetAttrString(py_base_module,"redirectStdErr");
             PyObject *pyerrormsg=PyObject_CallFunction(pyerrormsg_method, NULL);
             Py_DECREF(pyerrormsg_method);
             Py_DECREF(pyerrormsg);
             PyErr_Print();
             PyObject *pysys=PyObject_GetAttrString(py_base_module,"sys");
             PyObject *pystderr=PyObject_GetAttrString(pysys,"stderr");
             Py_DECREF(pysys);
             PyObject *pygetvalue=PyObject_GetAttrString(pystderr, "getvalue");
             Py_DECREF(pystderr);
             PyObject *pyres=PyObject_CallFunction(pygetvalue, NULL);
             Py_DECREF(pygetvalue);
             printf("%s\n", PyString_AsString(pyres));
             //test if we must send it to the page
             PyObject *pysendtraceback = PyObject_GetAttrString(py_config_module,"send_traceback_to_browser");
             cli->response_content=PyList_New(0);
             if (pysendtraceback==Py_True) {
                pydummy = PyString_FromString("<h1>Error</h1><pre>");
                PyList_Append(cli->response_content, pydummy );
                Py_DECREF(pydummy);
                PyList_Append(cli->response_content, pyres);
                pydummy = PyString_FromString("</pre>");
                PyList_Append(cli->response_content, pydummy);
                Py_DECREF(pydummy);
             } else {
                PyObject *pyshortmsg = PyObject_GetAttrString(py_config_module,"send_traceback_short");
                PyList_Append(cli->response_content, pyshortmsg);
                Py_DECREF(pyshortmsg);
             }
             Py_DECREF(pyres);
             Py_DECREF(pysendtraceback);
         }
         else 
         {
             cli->response_content=PyList_New(0);
             pydummy = PyString_FromString("Page not found.");
             PyList_Append(cli->response_content, pydummy );
             Py_DECREF(pydummy);
         }
    }
leave_python_handler:
    Py_XDECREF(pystart_response);
    Py_XDECREF(pyenviron);
    return 1;
}
Esempio n. 10
0
static PyObject* PyJudyIntSet_repr(PyJudyIntSet* set)
{
	if (!set->allow_print)
		return PyString_FromFormat("<%s object at %p>", Py_TYPE(set)->tp_name, (void*)set);

	char s_buffer[32];
	PyObject* retval = 0;
	PyObject* comma_space = 0;
	PyObject* s = 0;

	if (set->s == 0)
		return PyString_FromString("JudyIntSet([])");

	if ((comma_space = PyString_FromString(", ")) == 0)
		goto cleanup;

	retval = PyString_FromString("JudyIntSet([");

	if (retval == 0)
		goto cleanup;

	JError_t JError;
	Word_t v = 0;
	Judy1First(set->s, &v, &JError);

	sprintf(s_buffer, "%llu", (unsigned long long)v);
	s = PyString_FromString(s_buffer);

	if (s == 0) {
		Py_CLEAR(retval);
		goto cleanup;
	}

	PyString_ConcatAndDel(&retval, s);

	if (retval == 0)
		goto cleanup;

	while (1) {
		int i = Judy1Next(set->s, &v, &JError);

		if (i == 0)
			break;

		PyString_Concat(&retval, comma_space);

		if (retval == 0)
			goto cleanup;

		sprintf(s_buffer, "%llu", (unsigned long long)v);
		s = PyString_FromString(s_buffer);

		if (s == 0) {
			Py_CLEAR(retval);
			goto cleanup;
		}

		PyString_ConcatAndDel(&retval, s);

		if (retval == 0)
			goto cleanup;
	}

	s = PyString_FromString("])");

	if (s == 0)
		goto cleanup;

	PyString_ConcatAndDel(&retval, s);

cleanup:

	Py_XDECREF(comma_space);

	return retval;
}
Esempio n. 11
0
PyObject *ObjectRow_PyObject__subscript(ObjectRow_PyObject *self, PyObject *key)
{
    ObjectAttribute *attr = 0;
    PyObject *value, *pytmp;

    if (!self->query_info) {
        // If no query_info available, then we work strictly from the pickle
        // dict, which init() requires be available.
        value = PyDict_GetItem(self->pickle, key);
        if (!value) {
            PyErr_SetObject(PyExc_KeyError, key);
            return NULL;
        }
        Py_INCREF(value);
        return value;
    }

    // String is the more common case.
    if (PyString_Check(key)) {
        // Handle some special case attribute names.
        if (PyStr_Compare(key, "type") == 0) {
            // Returns the type name of this object.
            Py_INCREF(self->type_name);
            return self->type_name;

        } else if (PyStr_Compare(key, "parent") == 0) {
            /* Returns a tuple (type_name, id) for this object's parent.  If
             * type_name can't be resolved from the parent_id, then the integer
             * value for the type is used instead.
             */

            if (!self->parent) {
                // Generate the value if it's not available.
                ObjectAttribute *type_attr, *id_attr;
                PyObject *o_type, *o_id, *type_name = 0;

                // Lookup the parent_type and parent_id indexes within the
                // sql row.
                pytmp = PyDict_GetItemString(self->query_info->idxmap, "parent_type");
                type_attr = pytmp ? (ObjectAttribute *)PyCObject_AsVoidPtr(pytmp) : NULL;

                pytmp = PyDict_GetItemString(self->query_info->idxmap, "parent_id");
                id_attr = pytmp ? (ObjectAttribute *)PyCObject_AsVoidPtr(pytmp) : NULL;
                // If neither of these values are available in the row, raise an
                // exception.
                if (!type_attr || !id_attr || type_attr->index == -1 || id_attr->index == -1) {
                    PyErr_Format(PyExc_IndexError, "Parent attribute not available.");
                    return NULL;
                }
                // They're both available, so fetch them.
                o_type = PySequence_Fast_GET_ITEM(self->row, type_attr->index);
                o_id = PySequence_Fast_GET_ITEM(self->row, id_attr->index);
                // Resolve type id to type name.
                if (PyNumber_Check(o_type))
                    type_name = PyDict_GetItem(self->query_info->type_names, o_type);
                // Construct the (name, id) tuple.
                if (type_name)
                    self->parent = Py_BuildValue("(OO)", type_name, o_id);
                else
                    self->parent = Py_BuildValue("(OO)", o_type, o_id);
            }

            Py_INCREF(self->parent);
            return self->parent;
        }
        else if (PyStr_Compare(key, "_row") == 0) {
            Py_INCREF(self->row);
            return(self->row);
        }

        pytmp = PyDict_GetItem(self->query_info->idxmap, key);
        attr = pytmp ? (ObjectAttribute *)PyCObject_AsVoidPtr(pytmp) : NULL;
    }
    // But also support referencing the sql row by index.  (Pickled attributes
    // cannot be accessed this way, though.)
    else if (PyNumber_Check(key)) {
        long index = -1;
        if (PyInt_Check(key))
            index = PyInt_AsLong(key);
        else if (PyLong_Check(key))
            index = PyLong_AsLong(key);

        if (index < 0 || index >= PySequence_Length(self->row)) {
            PyErr_Format(PyExc_IndexError, "index out of range");
            return NULL;
        }
        return PySequence_GetItem(self->row, index);
    }

    //printf("REQUEST: %s attr=%p idx=%d has_pickle=%d pickle_idx=%d\n", skey, attr, attr->index, self->has_pickle, self->query_info->pickle_idx);

    if (attr && attr->index == -1 && !self->has_pickle && self->query_info->pickle_idx != -1) {
        /* Attribute is valid and pickle column exists in sql row, but pickle
         * is None, which means this attribute was never assigned a value, so
         * return suitable default ([] for ivtidx, and None for everything
         * else)
         */
        return get_default_for_attr(attr);
    }

    /* Raise exception if attribute name isn't known, or if the requested
     * attribute, while valid for this object type, can't be obtained given the
     * query that was done.
     */
    if (!attr || (attr->index == -1 && !self->has_pickle && attr->pickled)) {
        PyErr_SetObject(PyExc_KeyError, key);
        return NULL;
    }

    if (!attr->pickled || (IS_ATTR_INDEXED_IGNORE_CASE(attr->flags) && attr->index >= 0 && !self->has_pickle))
        /* If the attribute isn't pickled, we return the value from the row
         * tuple.  Also, if the attribute is ATTR_INDEXED_IGNORE_CASE but we
         * don't have a pickle available, and that attribute exists in the
         * row tuple, return what we have.
         */
        return convert(self, attr, PySequence_Fast_GET_ITEM(self->row, attr->index));

    // If we need to check the pickle but haven't unpickled, do so now.
    if (!self->unpickled && !do_unpickle(self))
        return NULL;

    if (IS_ATTR_INDEXED_IGNORE_CASE(attr->flags)) {
        // ATTR_INDEXED_IGNORE_CASE, these attributes are prefixed with __ in
        // the pickled dict.
        PyObject *newkey = PyString_FromString("__");
        PyString_Concat(&newkey, key);
        key = newkey;
    }
    else
        Py_INCREF(key);

    value = PyDict_GetItem(self->pickle, key);
    Py_DECREF(key);
    if (!value)
        // Attribute isn't stored in pickle, so return suitable default.
        return get_default_for_attr(attr);

    return convert(self, attr, value);
}
Esempio n. 12
0
static PyObject *
attr_dir_repr(PyObject *_self)
{
	attr_dir_object *self = (attr_dir_object*)_self;
	kdump_ctx *ctx = self->kdumpfile->ctx;
	kdump_attr_iter_t iter;
	kdump_status status;
	PyObject *s, *temp;
	PyObject *colon = NULL, *pieces = NULL;
	PyObject *result = NULL;
	int res;

	status = kdump_attr_ref_iter_start(ctx, &self->baseref, &iter);
	if (status != kdump_ok) {
		PyErr_Format(exception_map(status), kdump_err_str(ctx));
		return NULL;
	}

	if (!iter.key) {
		result = PyString_FromFormat("%s({})",
					     Py_TYPE(_self)->tp_name);
		goto out;
	}

	colon = PyString_FromString(": ");
	if (!colon)
		goto out;

	pieces = PyList_New(0);
	if (!pieces)
		goto out;

	while (iter.key) {
		s = PyString_FromString(iter.key);
		if (!s)
			goto out;
		temp = attr_dir_subscript(_self, s);
		if (!temp) {
			Py_DECREF(s);
			goto out;
		}
		PyString_Concat(&s, colon);
		PyString_ConcatAndDel(&s, PyObject_Repr(temp));
		Py_DECREF(temp);
		if (!s)
			goto out;

		res = PyList_Append(pieces, s);
		Py_DECREF(s);
		if (res <0)
			goto out;

		status = kdump_attr_iter_next(ctx, &iter);
		if (status != kdump_ok) {
			PyErr_Format(exception_map(status), kdump_err_str(ctx));
			goto out;
		}
	}

	s = PyString_FromFormat("%s({", Py_TYPE(_self)->tp_name);
	if (!s)
		goto out;
	temp = PyList_GET_ITEM(pieces, 0);
	PyString_ConcatAndDel(&s, temp);
	PyList_SET_ITEM(pieces, 0, s);
	if (!s)
		goto out;

	s = PyString_FromString("})");
	if (!s)
		goto out;
	temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
	PyString_ConcatAndDel(&temp, s);
	PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
	if (!temp)
		goto out;

	s = PyString_FromString(", ");
	if (!s)
		goto out;
	result = _PyString_Join(s, pieces);
	Py_DECREF(s);

 out:
	kdump_attr_iter_end(ctx, &iter);
	Py_XDECREF(pieces);
	Py_XDECREF(colon);
	return result;
}
// @pymethod |PyIDirectSoundCaptureBuffer|Update|Retrieve data from the capture buffer.
PyObject *PyIDirectSoundCaptureBuffer::Update(PyObject *self, PyObject *args)
{
  // @pyparm int|dwReadCursor||Offset, in bytes, from the start of the buffer to where the update begins.

  // @pyparm int|dwReadBytes||Size, in bytes, of the portion of the buffer to update. 

  // @pyparm int|dwFlags|0|Flags modifying the update event. This value can be 0 or the following flag: DSCBLOCK_ENTIREBUFFER  
  // The dwReadBytes parameter is to be ignored and the entire capture buffer is to be locked. 

	DWORD dwReadCursor = 0;
	DWORD dwReadBytes = 0;
	DWORD dwFlags = 0;
	IDirectSoundCaptureBuffer *pIDSCB = GetI(self);
	if ( pIDSCB == NULL )
		return NULL;
	if ( !PyArg_ParseTuple(args, "ii|i:Update", &dwReadCursor, &dwReadBytes, &dwFlags) )
		return NULL;

	HRESULT hr;
	LPVOID lpAudioPtr1 = NULL;
	DWORD dwAudioBytes1 = 0;
	LPVOID lpAudioPtr2 = NULL;
	DWORD dwAudioBytes2 = 0;

	PY_INTERFACE_PRECALL;
	hr = pIDSCB->Lock(dwReadCursor, dwReadBytes, &lpAudioPtr1, &dwAudioBytes1,
		&lpAudioPtr2, &dwAudioBytes2, dwFlags);
	PY_INTERFACE_POSTCALL;

	if (FAILED(hr)) {
		PyWin_SetAPIError("Update(Lock)", hr);
		return NULL;
	}

	// The capture buffer is circular, so we may get two pointers and have to 
	// do the wrap-around ourselves.

	PyObject *obData = PyString_FromStringAndSize((char*)lpAudioPtr1, dwAudioBytes1);
	if (!obData)
	{
		PyErr_SetString(PyExc_MemoryError, "Update: could not allocate result string");
		goto error;
	}
	if (lpAudioPtr2)
	{
		PyObject *obData2 = PyString_FromStringAndSize((char*)lpAudioPtr2, dwAudioBytes2);
		
		PyString_Concat(&obData, obData2);
	
		if (!obData)
		{
			PyErr_SetString(PyExc_MemoryError, "Update: could not append to result string");
			goto error;
		}
	}

	{
		// need extra block for local variables from PY_INTERFACE_UPCALL macro
		PY_INTERFACE_PRECALL;
		hr = pIDSCB->Unlock(lpAudioPtr1, dwAudioBytes1, lpAudioPtr2, dwAudioBytes2);
		PY_INTERFACE_POSTCALL;
	}

	if (FAILED(hr)) {
		Py_DECREF(obData);
		PyWin_SetAPIError("Update(Unlock)", hr);
		return NULL;
	}

	return obData;

error:
	{
		// need extra block for local variables from PY_INTERFACE_UPCALL macro
		PY_INTERFACE_PRECALL;
		hr = pIDSCB->Unlock(lpAudioPtr1, dwAudioBytes1, lpAudioPtr2, dwAudioBytes2);
		PY_INTERFACE_POSTCALL;
	}

	return NULL;
}