Passed
Push — master ( 0b1002...3924a5 )
by Marcin
02:49
created

fetch_pdb_header()   A

Complexity

Conditions 3

Size

Total Lines 53
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 14
nop 1
dl 0
loc 53
rs 9.7
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
"""
4
5
"""
6
from __future__ import print_function
7
import argparse
8
from icecream import ic
9
import sys
10
ic.configureOutput(outputFunction=lambda *a: print(*a, file=sys.stderr))
11
ic.configureOutput(prefix='> ')
12
13
14
def get_parser():
15
    parser = argparse.ArgumentParser(
16
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
17
    #parser.add_argument('-', "--", help="", default="")
18
    parser.add_argument("-v", "--verbose",
19
                        action="store_true", help="be verbose")
20
    parser.add_argument("file", help="", default="", nargs='+')
21
    return parser
22
23
import requests
24
25
def fetch_pdb_header(pdb_id):
26
    """
27
    Fetches the header information for a given PDB ID using the RCSB PDB GraphQL API.
28
29
    :param pdb_id: The PDB ID to query.
30
    :return: A dictionary containing the header information or an error message.
31
    """
32
    # Define the GraphQL query
33
    query = """
34
    query getPDBHeader($id: String!) {
35
      entry(entry_id: $id) {
36
        rcsb_id
37
        struct {
38
          title
39
        }
40
        exptl {
41
          method
42
        }
43
        rcsb_accession_info {
44
          deposit_date
45
          initial_release_date
46
        }
47
        citation {
48
          title
49
          rcsb_authors
50
          year
51
          pdbx_database_id_DOI
52
        }
53
      }
54
    }
55
    """
56
    
57
    # Define the variables
58
    variables = {"id": pdb_id}
59
    
60
    # API endpoint
61
    url = "https://data.rcsb.org/graphql"
62
    headers = {"Content-Type": "application/json"}
63
    
64
    try:
65
        # Send the POST request
66
        response = requests.post(url, json={"query": query, "variables": variables}, headers=headers)
67
        response.raise_for_status()  # Raise HTTPError for bad responses (4xx and 5xx)
68
        data = response.json()
69
        
70
        # Return the data or error
71
        if "data" in data:
72
            return data["data"]
73
        else:
74
            return {"error": "No data returned. Check the PDB ID or API response."}
75
    
76
    except requests.exceptions.RequestException as e:
77
        return {"error": str(e)}
78
    
79
80
if __name__ == '__main__':
81
    parser = get_parser()
82
    args = parser.parse_args()
83
84
    if list != type(args.file):
85
        args.file = args.file
86
 
87
    for pdb_id in [f.replace('.pdb', '').replace('.cif', '') for f in args.file]:
88
        header_info = fetch_pdb_header(pdb_id)
89
        title = header_info.get('entry', {}).get('struct', {}).get('title', 'Title not found')
90
        # Print the extracted title
91
        print(pdb_id, title)
92